Let’s start with a simple example. Say we want to create a function that requests an URL and tells us the status code. Using ES6 promises this is what the code might look like:

const https = require('https');

function request(url) {
  return new Promise((resolve, reject) => {
    https.get(url, response => resolve(response));
  });
}

function getStatus(url) {
  console.log(`Started fetching ${url}`);
  request(url).then(({ statusCode }) => {
    console.log(`Responded with ${statusCode}`);
  });
}

getStatus('https://richardkall.se');

With async/await we can simplify the getStatus function a bit. Instead of calling .then() we can rewrite it as a async function and await for the request to be resolved.

async function getStatus(url) {
  console.log(`Started fetching ${url}`);
  const { statusCode } = await request(url);
  console.log(`Responded with ${statusCode}`);
}

It will wait for the promise to resolve in a non-blocking way. However, when trying to run this with node async-await-example you will get an error.

async function getStatus (url) {
 ^^^^^^^^
SyntaxError: Unexpected token function

The good news is that async/await has landed in v8 of the JavaScript engine, which is implemented in Node 7. Async/await is added as a experimental feature and can be used with the flag --harmony-async-await.

Start using async/await today by installing Node 7 and running it with:

node --harmony-async-await