How to Use Async/Await in JavaScript

In this tutorial, we will learn How to Use Async/Await in JavaScript

Here we have some easy and efficient method to find out.

 How to Use Async/Await in JavaScript

Usage of Async : 

async function greet() {
  return "Hello, world!";
}

// Calling the async function
greet().then(message => console.log(message)); 

Output:

 Hello, world!

Explanation:

For instance, in the async keyword, a function is named greet and it returns a Promise. It must be noted that the function immediately sends a string “Hello, world!” inside of the Promise to allow its asynchronous handling. Whenever you call greet a promise would be returned by JavaScript with the value “Hello, world!”. You can use .then() method to handle resolved values and output messages on console. This illustrates how async functions return Promises by default thus allowing developers write more readable code for asynchronous operations.

Usage of Await :

function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function displayMessage() {
  console.log("Waiting...");
  await delay(2000); // Wait for 2 seconds
  console.log("Done waiting!");
}

displayMessage();

Output:

 Waiting...
(waits for 2 seconds)
 Done waiting!

Explanation:

In the example given here, delay function returns a Promise that resolves after some time. The async function displayMessage pauses for two seconds using await  until the delay Promise is resolved. First it prints “Waiting…” then waits for two seconds and thereafter prints “Done waiting!”. This demonstrates how await stops execution in asynchronous operations making the code more readable.

 

Leave a Reply

Your email address will not be published. Required fields are marked *