DEV Community

Joseph Hughes
Joseph Hughes

Posted on • Originally published at joehughes.dev

Async and Await Quick Guide

Async and Await were introduced as ways to reduce headaches around nested callbacks. Async/Await is another way for you to wait for a result to return before continuing. At a basic level they are a keyword put before a function and then another keyword put before a promise that forces JavaScript to wait for that promise to return it's results.

async function functionName(){
  let value = await functionReturningPromise();
}

// arrow syntax
let functionName = async () => {
   let value = await functionReturningPromise();
}

Currently, awaits are limited in being used from inside of an async function, however there is an update coming to allow for awaits to be used at the top level of your code. This will remove the need for await to be inside of an async function.

Async/Await can also be used inside of a class by putting async on the method similar to how you would a function.

class ClassName{
  async methodName(){
    let value = await functionReturningPromise();
  }
}

On common thing people forget to do with the new syntax is to catch your errors. This is simple, simply wrap the await inside of a try..catch

async function functionName(){
  try{
    let value = await functionReturningPromise();
  } catch(err) {
    // handle err here
    console.log('error: ' , err);
  }
}

Also you can have multiple awaits inside the same function. The 2nd await will not run until the 1st await finishes.

async function functionName(){
  try{
    let value = await functionReturningPromise();
    let finalResult = await functionReturningPromiseTwo(value);
  } catch(err) {
    // handle err here
    console.log('error: ' , err);
  }
}

Async/Await is nothing to be afraid of, in fact it will simplify your code by reducing nested callbacks.

Top comments (0)