首頁  >  文章  >  web前端  >  如何在 TypeScript 中建立非同步函數?

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

WBOY
WBOY轉載
2023-08-30 22:13:021550瀏覽

如何在 TypeScript 中创建异步函数?

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

在開始之前,我們先來了解一下非同步程式設計和函數的需求。當我們從API取得資料時,需要一些時間來回應。現在,我們需要在應用程式中使用從 API 獲得的結果。

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

當我們使函數非同步時,它會暫停特定程式碼區塊的執行,直到我們從 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關鍵字只是暫停非同步函數的執行,其他程式碼可以繼續執行。一旦承諾解決,它就會再次開始執行。

現在,讓我們透過不同的例子來了解非同步函數的概念。

範例

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

在輸出中,使用者可以觀察到它在列印函數中資料變數的值之前列印了「函數執行後」。因此,我們可以從中了解到,當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。此外,我們也從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 關鍵字並承諾從中獲取資料。非同步函數提高了單線程應用程式的效能。

以上是如何在 TypeScript 中建立非同步函數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除