'Need Promise.all but without running in parallel

How do I make the last console.log line of the code snippet execute only after ALL the updateInkLevel functions finish executing?

  for (let i = 0; i < activeDevices.length; i++) {

    updateInkLevel(accessToken, deviceId, logIndex) 
    await new Promise((r) => setTimeout(r, 500)) // add a small sleep delay
  }
  console.log("everything completed")

updateInkLevel is an async function, returning a promise. I was thinking of using Promise.all, but that would run each iteration in parallel, which is not I want here. Here, I'm firing each iteration sequentially one at a time, with a small sleep delay before firing the next call.

I'm looking for something like Promise.all, but without running in parallel.

References, Is Node.js native Promise.all processing in parallel or sequentially?



Solution 1:[1]

await new Promise((r) => setTimeout(r, 500)) // add a small sleep delay

Don't do that.

You are guessing how long updateInkLevel will take


Just await the promise returned by updateInkLevel.

That will pause the loop until the promise resolves.


I was thinking of using Promise.all, but that would run each iteration in parallel, which is not I want here.

Are you sure you don't want them in parallel? That would often be more efficient.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1