DEV Community

Cover image for Speed up Promises in JavaScript
Huzaima Khan
Huzaima Khan

Posted on • Originally published at huzaima.io

Speed up Promises in JavaScript

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 };
}
Enter fullscreen mode Exit fullscreen mode

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,
  ]);
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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?

Top comments (0)