首页  >  文章  >  web前端  >  如何在 TypeScript 中创建异步函数?

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

WBOY
WBOY转载
2023-08-30 22:13:021553浏览

如何在 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删除