Skip to content

Instantly share code, notes, and snippets.

@raynerpupo
Created April 17, 2018 03:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raynerpupo/844607a20fd74e7a351f1d4113724989 to your computer and use it in GitHub Desktop.
Save raynerpupo/844607a20fd74e7a351f1d4113724989 to your computer and use it in GitHub Desktop.

Async / Await

Async and await let us handle asynchronous code easily, it's somehow similar to generators, pausing the execution whenever the await is prefixed:

// To be able to wait for a call we need to mark a function as async
async function getTemperature () {
// We wait until the getWeather function returns the value
  const weather = await getWeather(....);
  
// Once the value is ready the execution is resumed and we can use the result
  return weather.temperature;
}

Promise compatibility

An async function can be piped like a promise

getTemperature().then(console.log);

Error handling

As for Promise piping, the easiest way to handle possible errors is using the .catch clause.

getTemperature()
  .then(console.log)
  .catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment