Async / Await in Javascript

Hi, async / await is part of ES8 and is a different way to write an Asynchronous function that return a Promise and make the things easy and nice to follow, this new way is non blocking (like Promises and callbacks).

Note: This is not a new functionality of Asynchronous, is just a different way to write Asynchronous function that will return us a Promise.

async

The syntax to write a Asynchronous function is this:

async function myFunction() {}

And we can use the await expression inside our function; this “await” will pause our async function and will wait for the Promise (because this way return us a Promise) to resolve. 

Example:

const myResult = async () => {
  return 'Im the result';
}

myResult().then((result) => {
  console.log('result ==>', result);
});

Result:

Await 

It makes the code wait until the Promise returns a result. The “await” only makes the async block await. 

Example:

const myResult = async () => {
  const text = await 'Im the result';
  return console.log('text ->', text);
}

console.log(1);
myResult();
console.log(2);

Result:

Or the same example can be like this (because is a JS Promise) and we will have the same result:

const myResult = async () => {
  const text = await 'Im the result';
  return text;
}

console.log(1);

myResult().then(r => console.log('result-->', r));

console.log(2);

Remember we can’t use the await keyword inside of regular functions.

By Cristina Rojas.