Async Await

What is Async-Await

ES8 provides a new syntax for handling our asynchronous action, async...await.

async Keyword

The async keyword ensures that the function returns a promise.

Syntax

async function myFunc() {
  // Function body here
};

myFunc();

We can also create async function expressions:

const myFunc = async () => {
  // Function body here
};

myFunc();

async functions always return a promise, so we can use traditional promise syntax, like .then() and .catch

async function fivePromise() { 
  return 5;
}

fivePromise()
.then(resolvedValue => {
    console.log(resolvedValue);
  })  // Prints 5

await Operator

await is an operator used only inside an async function, and halts the execution of a function until a given promise is no longer pending.

await returns the resolved value of the awaited promise.

The await keyword waits until that promise settles, and then:

  • Returns the result
  • If it’s an error, the exception is generated.
async function f() {

  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("done!"), 1000)
  });

  let result = await promise; // wait until the promise resolves (*)

  alert(result); // "done!"
}

f();

If a promise resolves normally, then await promise returns the result. However, in the case of a rejection, it throws the error.

async function f() {
  await Promise.reject(new Error("Whoops!"));
}

is the same as:

async function f() {
  throw new Error("Whoops!");
}

Handling errors

With async…await, we use try…catch statements for error handling.

async function usingTryCatch() {
 try {
   let resolveValue = await asyncFunction('thing that will fail');
   let secondValue = await secondAsyncFunction(resolveValue);
 } catch (err) {
   // Catches any errors in the try block
   console.log(err);
 }
}

usingTryCatch();

await and Promise.all()

async function asyncPromAll() {
  const resultArray = await Promise.all([asyncTask1(), asyncTask2(), asyncTask3(), asyncTask4()]);
  for (let i = 0; i<resultArray.length; i++){
    console.log(resultArray[i]); 
  }
}