Async Await in ES6

A promise can either resolve to a value or reject with an error. Async/await lets you handle these cases with synchronous operators: assignment for resolved values, and try/catch for exceptions. The return value of await is the value that the promise resolves to:

async function test() {
  const res = await new Promise(resolve => {
    // This promise resolves to "Hello, World!" after ~ 1sec
    setTimeout(() => resolve('Hello, World!'), 1000);
  });
  // Prints "Hello, World!". `res` is equal to the value the promise resolved to
  console.log(res);
}

test();

In an async function, you can use try/catch to catch promise rejections. In other words, asynchronous promise rejections behave like synchronous errors:

async function test() {
  try {
    await new Promise((resolve, reject) => {
      setTimeout(() => reject(new Error('Woops!')), 1000);
    });
  } catch (error) {
    // Prints "Caught Woops!"
    console.log('Caught', error.message);
  }
}

test();

await must not be in a closure embedded in an async function, unless the closure is also an async function. The below code also results in a SyntaxError:

const assert = require('assert');

async function test() {
  const p = Promise.resolve('test');
  assert.doesNotThrow(function() {
    // SyntaxError: Unexpected identifier
    await p;
  });
  console.log('Hello, world!');
}

test();

Using await with any object that has a then() function will work:

async function test() {
  // This object is a "thenable". It's a promise by the letter of the law,
  // but not the spirit of the law.
  await { then: resolve => setTimeout(() => resolve(), 1000) };
  console.log('Hello, World!');
}

test();

ref: http://thecodebarbarian.com/80-20-guide-to-async-await-in-node.js.html
Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s