async await Example | JavaScript

Last modified: September 14, 2019

let asyncActivity = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(1), 5000)
  })
}

async function myFunction() {
  let result = await asyncActivity();
  console.log("result is: " + result)
}

myFunction()

The async and await keywords are syntactic sugar for Promises in JavaScript.

The same function could be written as:

function myFunction() {
  asyncActivity()
  .then(result => console.log(result))
}

When async is specified at the beginning of a function, await can be used as an alternative to then().

async/await presents a cleaner syntax for working with promises. This is especially true with Promise chaining...

//Promise chaining using traditional then()
function myFunction(){
  async1()
  .then(result1 => async2(result1))
  .then(result2 => async3(result2))
  .then(result3 => console.log(result3))
}

//Promise chaining using async/await
async function myFunction(){
  let result1 = await async1()
  let result2 = await async2(result1)
  let result3 = await async3(result2)
  console.log(result3)
}

async await vs promises

Using async/await is the same as using a Promise. async/await is simply syntactic sugar for a Promise.

async await arrow function

You can define an async / await function using the ES6 arrow syntax...

let myFunction = async () => {
  let result = await asyncActivity();
  console.log("result is: " + result)
}

async await try catch

If a Promise rejects within an async/await method, it can be captured inside a regular try..catch block...

try {
  myFunction()
} catch(e) {
  console.log(e)
}

You might also like: