异步编程允许我们并行执行多个任务。我们可以使用 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 中创建异步函数?的详细内容,更多请关注编程之家其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。