如何在TypeScript中建立非同步函式?


非同步程式設計允許我們並行執行多個任務。我們可以使用async/await關鍵字來使函式非同步。

在我們開始之前,讓我們瞭解非同步程式設計和函式的需求。當我們從API獲取資料時,需要一些時間才能響應。現在,假設我們需要在我們的應用程式中使用從API獲取的結果。

像TypeScript和JavaScript這樣的單執行緒程式語言永遠不會停止程式碼的執行。因此,它不會等待API的響應,並開始對空值執行某些操作。

當我們使函式非同步時,它會暫停特定程式碼塊的執行,直到我們從API收到響應。因此,我們可以操作資料,而不是操作空值。

語法

使用者可以按照以下語法在TypeScript中使函式非同步。

async function func1() {
   await resolvePromise();
   // this code will not be executed until the promise is resolved
}

func1();
// this code will execute even if the promise is not resolved.

在上面的語法中,我們在函式之前使用了async關鍵字來使其非同步。此外,我們使用了await關鍵字來暫停函式的執行,直到我們從promise收到響應。

因此,await關鍵字只暫停非同步函式的執行,而其他程式碼可以繼續執行。一旦promise解析,它將再次開始執行。

現在,讓我們透過不同的例子學習非同步函式的概念。

示例

在這個例子中,我們使用async關鍵字建立了非同步測試函式。在test()函式中,我們使用了await關鍵字來暫停函式一段時間。

在輸出中,使用者可以觀察到它在列印函式中data變數的值之前列印了“函式執行後”。因此,我們可以從中學習的是,當await關鍵字暫停函式的執行時,它開始執行其他程式碼,這提高了應用程式的效能。

async function test(): Promise {
   let data: string = await "default string";
   console.log("The value of data is " + data);
}

console.log("Before function execution");
test();
console.log("After function execution");

編譯後,它將生成以下JavaScript程式碼:

"use strict";
async function test() {
   let data = await "default string";
   console.log("The value of data is " + data);
}
console.log("Before function execution");
test();
console.log("After function execution");

輸出

以上程式碼將產生以下輸出:

Before function execution
After function execution
The value of data is default string

示例2

在這個例子中,samplePromise()函式包含promise。我們使用了Promise建構函式來建立和解析promise。此外,我們還從samplePromise()函式返回了promise。

executeAsync()函式使用await關鍵字來呼叫samplePromise()函式。使用者可以在輸出中觀察到,await關鍵字會暫停executeAsync()函式的執行,直到promise完成。

async function samplePromise() {
   const new_promise = new Promise(function (resolve, reject) {
      resolve("Successfully resolved");
   });
   return new_promise;
}

async function executeAsync() {
   try {
      let response = await samplePromise();
      console.log(response);
   } catch (err) {
      console.log("Error is " + err);
   }
}
console.log("Before calling a function");
executeAsync();
console.log("After calling a function");

編譯後,它將生成相同的JavaScript程式碼:

async function samplePromise() {
   const new_promise = new Promise(function (resolve, reject) {
      resolve("Successfully resolved");
   });
   return new_promise;
}

async function executeAsync() {
   try {
      let response = await samplePromise();
      console.log(response);
   } catch (err) {
      console.log("Error is " + err);
   }
}
console.log("Before calling a function");
executeAsync();
console.log("After calling a function");

輸出

它將產生以下輸出:

Before calling a function
After calling a function
Successfully resolved

在本教程中,使用者學習瞭如何建立非同步函式。此外,我們學習瞭如何將async/await關鍵字與promise一起使用以獲取資料。非同步函式提高了單執行緒應用程式的效能。

更新於:2023年2月21日

6K+ 瀏覽量

啟動你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.