Concurrent request for API calls

Viewed 58

I want to call API in 3 concurrent requests but as soon as one of them is free, I want another request to go in. Right now I'm doing 3 request in promise all but it waits for all 3 to be done.

What is the best way to implement the correct 3 concurrent reqeusts?

const productsQuery = await getAllProducts();
const products = splitArrayIntoChunksOfLen(productsQuery.rows, 3);
for (let index = 0; index < products.length; index++) {
      const prodArr = products[index];

      const promises = prodArr.map((item) => callCustomAPI(item));

      await Promise.all(promises);
 }
1 Answers

There already exists a library for that. It is called p-limit.

import pLimit from 'p-limit';

const limit = pLimit(CONCURRENT_REQUESTS);

const input = [
    limit(() => fetchSomething('foo')),
    limit(() => fetchSomething('bar')),
    limit(() => doSomething())
];

// Only $CONCURRENT_REQUESTS promises are run at once
const result = await Promise.all(input);
console.log(result);
Related