0

I have a very special scenario where I have n number of object arrays. Then, I need to make n number of API calls. Currently, I'm using Promise.all as shown in code sample below.

const requests = [];
for (let i = 0; i < cache.length; i++) {
  requests.push(request.handleCache(cache[i]));
}
await Promise.all(requests);

As I understand, Promise.all will dispatch all requests concurrently, which means server will receive the requests in any order, right. But I need to receive the requests from server in the order as it is in cache because I have to handle the requests in the same order on my server. How can I send the requests one after another sequentially?

Nan Da
  • 107
  • 1
  • 4
  • It's totally understandable you wouldn't realize it, but it's **this** easy: `const results = []; for (let i = 0; i < cache.length; i++) { results[i] = await request.handleCache(cache[i]); }` (assuming you need to remember the results somewhere) or `for (let i = 0; i < cache.length; i++) { await request.handleCache(cache[i]); }` if you don't. :-) Note in both cases the `await` is inside tthe loop. `async` functions enable asynchronous code to use standard flow-control structures. – T.J. Crowder Aug 06 '21 at 16:51
  • I'm not a master on JS, but I think you should do the request synchronous – Bodok Aug 06 '21 at 16:51
  • 1
    @Dosbodoke - Synchronous requests tie up the main JavaScript/UI thread for the tab, which is generally a Bad Thing™. :-) Since the OP is already using an `async` function, there's no need anyway. – T.J. Crowder Aug 06 '21 at 16:52

0 Answers0