Speed up Promises in JavaScript

Huzaima KhanAug 07, 20222 min read

Promises are an integral part of async code in JavaScript. We often come across the need to run multiple promises at a time that are independent of each other. We can achieve this by using JavaScript's Promise.all. Promise.all is a promise provided by JavaScript that accepts an array of promises and resolves when all of them get resolved.

Suppose you've to fetch data from 3 different APIs. Each API takes around 3 seconds to respond. A normal code without concurrency would look like this:

The code above works fine. But can be improved by leveraging concurrency. We don't need to run them sequentially since all the three functions are independent of each other. We don't need metadata before products. We can rewrite the above code snippets like this:

Now we're not waiting for metadata before products. Instead, all the data gets fetched simultaneously. This technique is quite powerful and speed-up your code. This technique can also fetch the data based on a certain input. Suppose you want to fetch product details for a list of products. You can refactor your promises like this:

As JavaScript is single-threaded, parallelism cannot be achieved unless you create a child process for each promise. Spawning a process is a costly operation and there are certain overheads which make it less viable. Promise.all is a good alternative to achieve concurrency and speed up your code. Again, it depends upon the problem you're trying to solve. What techniques do you have to speed up promises in JavaScript?

Find me here:
GitHub  Twitter  LinkedIn  Instagram  Facebook

All Rights Reserved © Huzaima Khan 2023