Sitemap

Member-only story

Smarter use of await in Javascript

--

Not a member ? Read this for free !

You need results from 2 API calls.
You can code it like this:

const result1 = await fetch("https://abc.com");  // 500ms
const result2 = await fetch("https://xyz.com"); // 500ms

// Total time: 1 second

What’s the problem ?

  • We start the first one. Wait for it to finish.
  • Start the second one. Wait for it to finish.
  • Total time is 1 second (500ms + 500ms).

Smarter way:

const promise1 = fetch("https://abc.com");
const promise2 = fetch("https://xyz.com");

const [result1, result2] = await Promise.all([promise1, promise2]);

What changed ?

  • We don’t await immediately.
  • We fire both, wait for both to succeed

How’s this better?

  • Achieved concurrency 🎉
  • Each takes 500ms. They’re concurrent, so total time is also 500ms ! A 50% improvement in latency 🎉

What’s the catch ?

The above will throw if one of themreject s. If you don’t want this, use Promise.allSettled() instead:

const promise1 = fetch("https://abc.com");
const promise2 = fetch("https://xyz.com");

const [result1, result2]= await Promise.allSettled([promise1, promise2]);

if(result1.status === 'fulfilled') {
// Succeeded. Result is in result1.value
} else {
// Failed. Reason is in result1.reason
}

// do the same for result2

Notes:

  • The above can be applied to any async operation, not just API calls :)
  • To learn how this works on a deeper level, understand the event loop. See this video: What the heck is the event loop anyway?

--

--