Sitemap
Better Programming

Advice for programmers.

JavaScript: Promises or async-await

A set of rules for when to use which

4 min readAug 21, 2018

--

Press enter or click to view image in full size
Image

I recently read a medium post where the author claimed that using async-await is better than using promises.

While this might be true in general cases, I think that generalisation is too broad and doesn’t do justice to either async-await or promises.

For someone new to JavaScript, making sense of these and deciding which one to use can be a challenge. In this post, I will list things that I have learned about these and how I decide when to use which.

I read somewhere that async-await is syntactical sugar for using promises. So, before getting to know async-await or deciding which approach to use, make sure that you have a good understanding of promises and async-await.

Here are some thumb rules that I follow.

Thumb Rules for Using Promises

Press enter or click to view image in full size
Image
  1. Use promises whenever you are using asynchronous or blocking code.
  2. resolve maps to then and reject maps to catch for all practical purposes.
  3. Make sure to write both .catch and .then methods for all the promises.
  4. If something needs to be done in both cases use .finally.
  5. We only get one shot at mutating each promise.
  6. We can add multiple handlers to a single promise.
  7. The return type of all the methods in the Promise object, regardless of whether they are static methods or prototype methods, is again a Promise.
  8. In Promise.all, the order of the promises are maintained in the values variable, irrespective of which promise was first resolved.

Once you have wrapped your head around promises, check out async-await. It helps you to write code that is much more readable. When it is not used properly, it has its downsides.

Thumb Rules for async-await

Here’s a list of thumb rules that I use to stay sane while using async and await.

--

--

Responses (28)