如何在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一起使用以获取数据。异步函数提高了单线程应用程序的性能。
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP