{ Async / Await }

Promises are a tremendous feature to liberate yourself from the “callback hell” associated with asynchronous calls in jQuery or NodeJS callbacks. I usually setup an abstraction that handles the creation of the promise so it doesn’t need to clutter up the rest of the code.  For example, I create a DataStore class here with an api method using Axios:

import axios from "axios";

class DataStore {
  api( endPoint, method = 'get', data = null ) {
    return new Promise( ( resolve, reject ) => {
      axios[method]( endPoint, data ? data : '' ).then( ( response ) => {
      resolve( response.data );
    }).catch( ( error ) => {
      reject( error );
    });
  });
}

Then, for the simplest of GET calls, I only need to pass in the API endpoint and I get a promise back that I can return to the caller:

getSomething( id ) {
  return this.api( `myapipath.com/${id}` ).then( result => {
    return result.data;
  }).catch( error => {
    console.warn( error );
  })
}

Note that the above is a class method, otherwise you would need to do:

function getSomething(id) {}

– or –

const getSomething = id => {}

This has the tendency to get a bit tedious though, so given the right transpiler configuration you can make use of async / await now, which was introduced in ES7. This is even better, as we can turn an asynchronous function into one that is synchronous. Instead of not knowing when the function will return data to the caller, you can force it to wait, or await it. Thus we can use something as simple as this:

async getSomething( id ) {
  let response = await this.api( `myapipath.com/${id}` );
  if ( ! response.error ) {
    return response.data;
  }
}

Or you might want to wrap it in a try/catch block to catch any errors:

async getSomething( id ) {
  let response;
  
  try {
    response = await this.api( `myapipath.com/${id}` );
  } catch( e ) {
    console.warn( e.message );
  }

  return response.data;
}

The function has to be explicitly declared as async to let JS know to expect await. Also note that this is technically syntax sugar. It makes the function act like it is synchronous but we’re still fetching data here – it can’t be truly synchronous – but it is a big improvement upon back-to-back .then()’s.

This syntax makes it easier to do something else with the data before it’s returned. Suppose I need to only return data that has a specific attribute, like an id:

async getSomething( id ) {
  let response = await this.api( `myapipath.com/${id}` );
  return response.filter( data => data.id === id );
}

async/await

You should transpile, but all modern browsers at this point do support it natively, except for IE of course. Check it out on caniuse.com