DEV Community

Cover image for Async & Overview async/await
Jacob Evans
Jacob Evans

Posted on • Updated on

Async & Overview async/await

tl;dr async/await is a great way to deal with asynchronous behavior, once you get the hang of the syntax which I find more straightforward than <Promise>.then()


Syntatic Sugar!?

That's right you heard that correctly, Promises are abstractions on callbacks if you don't know those that's fine, I suggest eventually learning more on them. What async/await happens to be is the syntax to make dealing with promises and implementing certain behaviors.

Only Synchronous benefits? No.

So one of those behaviors is the quasi-synchronous execution of your calls. Which can be highly useful if you need certain data before another. However, if the data is not needed sequentially you can also allow parallel behavior by passing them into a Promise.all()

const data = await Promise.all([call1, call2]) 
Enter fullscreen mode Exit fullscreen mode

A great Stack Overflow Answer covers how Promise.all very thoroughly and even briefly talks about the fail fast

Node 12 async/await is faster than Promises...Seriously!

So async/await is syntactic sugar on Promises so Promises MUST be faster and more performant than async/await, well that isn't the case. If you want to delve deep down that rabbit hole I welcome you to it, I tried and my head hurts still lol


Promise Generator

I won't go too far into the details but async returns an AsyncFunction. However, with async you declare and it the function behaves far more synchronously it would look something like async function Something(){} this function now returns a Promise!


I also like to use try/catch for error handling with async/await.

async function someCall(someAPIURL) {
  const data = fetch(`${someAPIURL}`, { method: "GET" });
  return data;

let data;
  try {
data = await someCall(
} catch(error){
data = error

Enter fullscreen mode Exit fullscreen mode

Top comments (0)