Overview

Async / Await

  • Async / Await is special that makes working with promises easy to use and understand

  • The syntax and structure of Async / Await is makes our asynchronous handling look like synchronous code

  • Async / Await is alternative way of consuming promises a


async

  • In order for you to use Async / Await, you must declare a function with the async keyword

    async function someFunction() {
      return "something"
    }
    
  • Prepending async to a function declaration means that function always returns a promise


await

  • The keyword await makes JavaScript wait until that promise settles and returns its result

  • await can only be used in a function that is prepended with async

    • await will be ignored (and your code will not wait for the asynchronous action to complete) it you try to use await in a function that is not prepended with async

Example

function delayedGreeting() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('Hi, sorry for the wait!')
    }, 3000)
  });
}

/*
Declare function with "async" keyword
*/

async function msg() {
  // use "await" keyword to call promise and wait
  // for the result before moving on
  // to the next line of code
  const msg = await delayedGreeting()
  console.log(msg)
}

console.log("Calling msg()")
msg()
console.log("end of the code")

JS Bin on jsbin.com