Categories
Uncategorized

async & await in ES2017/ES8

async

Adding an async keyword to a function makes it asynchronous as the name itself suggests and it also return a promise instead of the value. We can define an ES6 function as async using the following syntax. This works with the old function syntax as well.

let myFunc = async() => {
  return 'Hi I am async!';
};
console.log(myFunc());
// logs Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: "Hi I am async!"}

/* Resolving a promise */
myFunc().then((result) => {
  console.log(result);
// logs: Hi I am async!
}).catch((err) => {
  console.log(err);
});

await

The await keyword can only be used inside an async function. When used, while calling an async function, it resolves the promise and returns the value.
The above code can be made more readable, by using the await keyword.

let myFunc = async() => {
  return 'Hi I am async!';
};
let finalSync = async() => {
  console.log(await firstAsyncFunc());
// logs: Hi I am async
};
finalSync();

Here is a live example of asynchronous functions in action. Although the first function is called first, we don’t have to wait until the promise is resolved to a result by await, instead we can see rest of the functions calls and their promises being resolved earlier.
Code

let firstAsyncFunc = async() => {
  setTimeout(function() {
    console.log('First');
  }, 3000);
};
let secondAsyncFunc = async() => {
  console.log('Second');
};
let thirdAsyncFunc = async() => {
  return 'Third';
};
let finalSync = async() => {
  await firstAsyncFunc();
  await secondAsyncFunc();
  console.log(await thirdAsyncFunc());
};
finalSync();

Output

Second
Third
First

Demo

Sequential calls vs Parallel calls

The following is an example of sequential asynchronous function calls

let finalSync = async() => {
  await firstAsyncFunc();
  await secondAsyncFunc();
};
finalSync();

If you want to make asynchronous function calls simultaneously, then you could use Promise.all and supply it with an array of asynchronous functions and then use await to return the result after all the calls are made.

let finalSync = async () => {
  await Promise.all([async1(), async2()]);
}
finalSync();