Javascript - Function Asynchronous Functions

Introduction

ES2017 introduces an new way of dealing with asynchronous code.

ES2017 makes asynchronous code in an synchronous manner using async and await keywords.

async always returns a promise, which can be resolved to a value and await suspends the execution until the promise is settled.

Here is an example with the async/await keywords:

async function getData(site) { 
   let request = await fetch(url); 
   let text = await request.text(); 
   return JSON.parse(text); 
} 

The await keyword works with promises only, and casts the expression into a promise if it's not one.

You can use async in function expressions, method definitions, and arrow functions like the following examples:

// Using function expression: 
const getData = async function () {}; 

// Using method definition: 
const item = { async getData() {} } 

// Using arrow function: 
const item = async () => {}; 

The await operator waits for the operand, the promise to be settled and if the promised is fulfilled.

Its result is the fulfillment value and if the promise is rejected, it throws the rejection value.

We can use a traditional try catch block with async/await to handle the promises in a better way.