3

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);
 }
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Mj Ebrahimzadeh
  • 587
  • 9
  • 22
  • 2
    Maybe you need [Promice.race](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race) instead? – evolutionxbox Sep 01 '22 at 11:29
  • 2
    Maybe you need [Async task manager with maximum number of concurrent "running" tasks](https://stackoverflow.com/questions/54901078/async-task-manager/54902235#)? – trincot Sep 01 '22 at 11:54
  • 1
    Does [this question and its answers](https://stackoverflow.com/q/73494026/) help? – Steve Sep 01 '22 at 14:50

1 Answers1

1

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);
Krzysztof Krzeszewski
  • 5,912
  • 2
  • 17
  • 30