Loading...
JavaScript

What is async/await in JavaScript

The async/await is a new feature included in ECMAScript 2017 or ES8 JavaScript edition in order to make asynchronous function calls easier and it act as syntactical sugar on top of promises. It allow us to write completely synchronous-looking code while performing asynchronous tasks behind the scenes.

The async Keyword:

The async is placed before a function to make it asynchronous. This means the function will always return a promise instead of returning a value directly. 

// Async function
async function greet() { 
   return "Hello world!"
};
greet();
// Output: Hello world!

Since the greet function is returning a promise, we could use a .then() block to consume the returned value. Let’s define the same function as function expression to understand this:

let greet = async function() { 
   return "Hello world!" 
};
greet().then(function(value){
   console.log(value);
})
// Output: Hello world!

// Using ES6 Arrow Function
greet().then((value) => console.log(value));

The code inside .then() does not get executed until the async greet function returns a value (i.e until the promise is fulfilled).

The await Keyword:

The keyword await makes JavaScript wait until that promise settles and returns its result. Note that await only works inside async functions. This can be put before any async promise based function to pause your code on that line until the promise fulfills and a value is returned. In the meantime, rest of the code may keep waiting for a chance to get execute.

let getGreeting = async function() { 
   // You can make some API call here and return the response  
   return "Hello world!" 
};

async function greet() {
   return greeting = await getGreeting();
};

greet().then(function(value){
   console.log(value);
})
// Output: Hello world!

As you have seen in the example above, async/await works closely together.

I will discuss about promise in detail in an upcoming article. Thank you for reading.

Share this article with your friends
Leave a Reply

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