ES6 includes a new way to handle functions that return a promise: Async functions!

Imagine we have a function get(url) which returns a promise to get the data at a given URL:

In ES5, we would have to do the following:

function getData() {
  get('http://somewebsite.com/data.json')
    .then(function(data) {
      // If the HTTP request succeeds, do stuff with the data here.
      console.log(data);
    })
    .catch(function(err) {
      // If the HTTP request fails, do something with the error here.
      console.log(err);
    });
}

In ES6 using Async functions, we can write this code in a clearer way:

async function getData() {
  try {
    // If the HTTP request succeeds, the script continues with the rest of the 'try' block.
    // If the HTTP request fails, the scripts jumps to the code in the 'catch' block.
    const data = await get('http://somewebsite.com/data.json');
    console.log(data);
  } catch (err) {
    console.log(err);
  }
}

ES6 allows you to write Async arrow functions as well:

const getData = async () => {
  try {
    // If the HTTP request succeeds, the script continues with the rest of the 'try' block.
    // If the HTTP request fails, the scripts jumps to the code in the 'catch' block.
    const data = await get('http://somewebsite.com/data.json');
    console.log(data);
  } catch (err) {
    console.log(err);
  }
};