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:
async function fetchData() {
const metadata = await getMetadata();
const products = await getProducts();
const categories = await getCategories();
return { metadata, products, categories };
}
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:
async function fetchData() {
const metadata = getMetadata();
const products = getProducts();
const categories = getCategories();
return await Promise.all([
metadata,
products,
categories,
]);
}
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:
async function fetchProductDetails(ids) {
const productDetails = await Promise.all(
ids.map(id => getProduct(id))
);
return productDetails;
}
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 that 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?
Also Published Here