[JavaScript – ES2017] async/await

ES2015 introduced a Promise object to handle async operations. ES2017 adds the async function and await operator. Please look at the Promise if you are not familiar with it.

 

1. Why async/await?

The purpose of “async/await” is to simplify how to use promises synchronously.

 

2. Async function

In general, an “async” function will return a Promise object that will be resolved with the value by the async function.

Here is a short example.

let complexOperation = (value) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(value*2);
    }, 1000);
  });
};

let asyncTask = async function () {
  let a = await complexOperation(10);
  let b = await complexOperation(20);
  return a + b; // 10*2 + 20*2 = 60
}

console.log("Before");
asyncTask().then(data => {
  console.log(`Done: ${data}`);
})  
console.log("After");

 

3. await operator

The “await” expression pauses an async function execution until a Promise is resolved. So that you can call Promises in a synchronous way.

await” is

  • used only in the async function
  • used before a Promise

 

4. Handle rejected Promise with await

You can use try/catch or catch().

let complexOperation = (value) => {
  return new Promise((resolve, reject) => {
    reject(new Error('failed'));
  });
};

let asyncTask1 = async function () {
  try {
    await complexOperation(10);
  } catch(e) {
    console.log("try/catch", e);
  }
}
asyncTask1();

let asyncTask2 = async function () {
  await complexOperation(10).catch(e => console.log("catch()", e));
}
asyncTask2();

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s