How to create an asynchronous function in TypeScript?

WBOY
Release: 2023-08-30 22:13:02
forward
1530 people have browsed it

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

Asynchronous programming allows us to perform multiple tasks in parallel. We can make functions asynchronous using async/await keywords.

Before we begin, let’s first understand the requirements for asynchronous programming and functions. When we get data from the API, it takes some time to respond. Now, we need to use the results obtained from the API in our application.

Single-threaded programming languages like TypeScript and JavaScript never stop code execution. So instead of waiting for a response from the API, it starts performing some operations on the null value.

When we make a function async, it pauses the execution of a specific block of code until we get a response from the API. Therefore, we can manipulate the data instead of manipulating null values.

grammar

Users can make functions asynchronous in TypeScript by following the following syntax.

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.
Copy after login

In the above syntax, we have used the async keyword before the function to make it asynchronous. In addition, we also use the await keyword to pause the execution of the function until we get the response of the promise.

So, the await keyword only pauses the execution of the asynchronous function, and other code can continue to execute. Once the commitment resolves, it starts execution again.

Now, let us understand the concept of asynchronous functions through different examples.

Example

In this example, we created an asynchronous test function using the async keyword. In the test() function, we use the await keyword to pause the function for a period of time.

In the output, the user can observe that it prints "After function execution" before printing the value of the data variable in the function. So, we can understand from this that when the await keyword pauses the execution of a function, it starts executing other code, thereby improving the performance of the application.

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");
Copy after login

When compiled, it will generate the following JavaScript code -

"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");
Copy after login

Output

The above code will produce the following output -

Before function execution After function execution The value of data is default string
Copy after login

Example 2

In this example, the samplePromise() function contains the promise. We use the Promise constructor to create and resolve Promises. Additionally, we returned the promise from the samplePromise() function.

The executeAsync() function uses the await keyword to call the samplePromise() function. Users can observe in the output that the await keyword pauses the execution of the executeAsync() function until the promise is fulfilled.

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");
Copy after login

When compiled, it will generate the same JavaScript code -

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");
Copy after login

Output

It will produce the following output –

Before calling a function After calling a function Successfully resolved
Copy after login

In this tutorial, the user learned how to create an asynchronous function. Additionally, we learned to use the async/await keyword and commit to get data from it. Asynchronous functions improve the performance of single-threaded applications.

The above is the detailed content of How to create an asynchronous function in TypeScript?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!