Home  >  Article  >  Web Front-end  >  How to create an asynchronous function in TypeScript?

How to create an asynchronous function in TypeScript?

WBOY
WBOYforward
2023-08-30 22:13:021595browse

如何在 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.

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");

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");

Output

The above code will produce the following output -

Before function execution
After function execution
The value of data is default string

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");

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");

Output

It will produce the following output –

Before calling a function
After calling a function
Successfully resolved

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete