Home > Software design >  why is my async code inside for loop not running sequentially?
why is my async code inside for loop not running sequentially?

Time:02-21

Why do all my function calls get executed in parallel here when using await? What needs to be changed in order to start a function call once the previous is done?

    for (let collection of collections) {
      await this.updateListings(collection)
    }
    co

CodePudding user response:

In fact. your code is executed sequentially. How did you check that your code was running in parallel?

You can use Array.reduce to make it sequentially:

return collections.reduce((currentPromiseChain, collection) => {
    return currentPromiseChain.then(() => this.updateListings(collection));
}, Promise.resolve());

CodePudding user response:

Just add an await before the condition. This will ensure each loop finishes before continuing to the next one.

Note: not fully sure on the compatibility for this, you may need check for compatibility.

for await (let collection of collections) { //notice the await in this line.
    await this.updateListings(collection)
}

CodePudding user response:

In order to have multiple asynchronous tasks executed at once, you would wanna use Promise.all and git it your array of asynchronous tasks, like so:

await Promise.all(collections.map(c => this.updateListings(c)));
  • Related