How to create asynchronous function in TypeScript?


Asynchronous programming allows us to perform multiple tasks parallelly. We can use the async/await keyword to make the function asynchronous.

Before we start, let’s learn the need for asynchronous programming and function. It takes some time to respond when we fetch data from the API. Now, think we need to use the results in our app, which we get from API.

The single-threaded programming language like TypeScript and JavaScript never stops the execution of the code. So, It doesn’t wait for the response of the API and starts performing some operation on null values.

When we make the function asynchronous, it suspends the execution of a particular block of code until we get a response from the API. So, we can manipulate the data rather than manipulate the null values.

Syntax

Users can follow the syntax below to make the function asynchronous in 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.

In the above syntax, we have used the async keyword before the function to make it asynchronous. Also, we have used the await keyword to suspend the execution of the function until we get a response from the promise.

So, await keyword only suspends the execution of the asynchronous function, and other code can continue execution. Once the promise resolves, it starts execution again.

Now, let’s learn the asynchronous function’s concept via different examples.

Example

In this example, we have created the asynchronous test function using the async keyword. In the test() function, we used the await keyword to suspend a function for a while.

In the output, users can observe that it prints the ‘After function execution’ before printing the data variable’s value in the function. So, we can learn from this is when await keyword suspends the execution of the function, it starts executing the other code, which increases 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");

On compiling, 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 have used the Promise constructor to create and resolve the promise. Also, we have 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 suspends the execution of the executeAsync() function until the promise gets 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");

On compiling, 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, users learned to create an asynchronous function. Also, we learned to use the async/await keyword with the promise to get data from that. The asynchronous functions improve the performance of a single-threaded application.

Updated on: 21-Feb-2023

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements