Asynchronous iteration
Not all loop work the same in JavaScript. If you want an asynchronous loop you cannot use forEach
because it will execute each iteration independently, however if you use a for of
it will work as expected: it will await until the previous iteration has finished.
async () => { for (const e of elements) await getCloudData(e) }
Be aware that in the previous code you will have to wait for each promise to resolve sequentially, which may not be as efficient if all your calls are unrelated. In that scenario, I would recommend you to use Promise.all()
that would create parallel connections and will be just as late as the latest response.
async () => { let promises = [] for (const e of elements) promises.push(getCloudData(e)) await Promise.all(promises) }
Keep in mind that every browser has a specific limit to open parallel connections.
now does not work the comments? what a troll!
javanfever, long time no see!
Use pre tag for blocks of code. Links are automatic, as soon as they are not within a special tag.
Further details: Writing Code in Your Posts.
for this problem you can define a pair of functions
or use some libs like p-iteration or async-af.
https://github.com/toniov/p-iteration
https://async-af.js.org/index.html
Thank you for those links dude! The thing is that you cannot stop a forEach by definition, so at the end if we are not glad with that we can use what you posted or a for of.