JavaScript Async/Await
JavaScript Basics

JavaScript Async/Await

Simplifying JavaScript Promises with Async/Await

The async and await keywords in JavaScript simplify working with promises, making asynchronous code easier to write and read.

Using Async

Adding the async keyword before a function declaration automatically makes it return a promise.

Example Using Async:

async function myFunction()
{  return "Hello";}‍// Using the returned PromisemyFunction().then
(  value => console.log(value) // Prints "Hello");‍

This is equivalent to manually returning a resolved promise:function myFunction()

{  return Promise.resolve("Hello");

}

Using Await

The await keyword is used within an async function and pauses the execution of the function until a Promise is resolved.

Basic Usage of Await:

async function displayMessage() 

{  let myPromise = new Promise(resolve => 

{    setTimeout(() => resolve("I love You !!"), 3000); 

});  

document.getElementById("demo").innerHTML = await myPromise;}‍

displayMessage();

Here, displayMessage waits for myPromise to resolve before continuing execution.

Implementing Async/Await Without Reject

Often, you may only need to handle a resolved promise, omitting the reject function entirely.

Example Without Reject:

async function displayMessage()

{  let myPromise = new Promise(resolve =>

{    resolve("I love You !!");  });

document.getElementById("demo").innerHTML = await myPromise;

}

displayMessage();

Practical Examples Using Async/Await

Async/Await can be especially useful for handling operations like timeouts or HTTP requests.

Waiting for a Timeout with Async/Await:

async function displayAfterTimeout()

{  let myPromise = new Promise(resolve =>
{    setTimeout(() => resolve("I love You !!"), 3000);  

});

document.getElementById("demo").innerHTML = await myPromise;}

displayAfterTimeout();

Fetching a File with Async/Await:

async function getFile() 
let myPromise = new Promise(resolve => 
let req = new XMLHttpRequest();    

req.open('GET', "mycar.html");    req.onload = () =>

{   
if (req.status == 200) {      
resolve(req.response);     

} else 

{        resolve("File not Found");   
}   
};    req.send();  });  
document.getElementById("demo").innerHTML = await myPromise;}

getFile();

Browser Support

Introduced in ECMAScript 2017, the async and await keywords are supported in major browsers:

  • Chrome 55+
  • Edge 15+
  • Firefox 52+
  • Safari 11+
  • Opera 42+

Summary

The async and await keywords enhance the readability and maintainability of asynchronous code in JavaScript. By handling promises in a more synchronous manner, they help avoid the complexities associated with traditional promise chains and callbacks.

Take a look into your desired course