Jump to navigation

Async + Await

Allows us to write Promises in a synchronous-looking style. {% ihighlight js %} await {% endihighlight %} will effectively pause the function until the promise is settled.

* Note that the {% ihighlight js %} await {% endihighlight %} 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.

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

}

<p>Multiple promises</p>
``` js
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