Jump to Categories

Async + Await

Allows us to write Promises in a synchronous-looking style. await will effectively pause the function until the promise is settled.

* Note that the await keyword may only be used in functions marked with the async keyword.

Basic example.

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

async function asyncCall() {
  console.log('calling');
  var result = await resolveAfter2Seconds();
  console.log(result);
  // expected output: "resolved"
}

asyncCall();

Basic example with Axois (promise based)

async function test() {

    const a = await axios.get('whatever');
    doSomthing(a);

}

Basic example with try/catch.

async function test() {

    try {
        let a = await axios.get('whatever');
        document.write(a.data.value.joke);
    } 
    catch(err) {
        document.write(err);
    }

}

Multiple promises

async function test() {

    const promiseOne = axois.get('whatever');
    const promiseTwo = axois.get('whatever');

    try {
        const [one, two] = await Promise.all([promiseOne, promiseTwo]);
        const html = `<p>${one.fname}, ${two.fname}</p>`;
    } 
    catch(err) {
        document.write(err);
    }

}

See the Pen Async + Await by Shane Prendergast (@webknit) on CodePen.

References