3

I would like to invoke an asynchronous function n times, invoking each time only after the previous one has resolved.

This is the code that works:

async startGame() {
  for (let i = 0; i < this.totalNumberOfSets; i++) {
  await this.startSet();
  }
}

I would like to convert it to the Lodash function _.times.

I tried using this answer: Lodash: is it possible to use map with async functions?

this way:

async startGame() {
  await Promise.all(_.times(this.totalNumberOfSets, async () => {
    await this.startSet()
  }))
};

but all the function invoked immediately four times without waiting to resolve.

Also tried this:

  async startGame() {
   let resArray = [];
   await Promise.all(_.times(this.totalNumberOfSets, async () =>{
     let res = await this.startSet()
     resArray.push(res);
    }
  ))
 };

but it didn't work as expected as well.

noam steiner
  • 4,034
  • 3
  • 27
  • 42
  • Possible duplicate of [How to synchronize a sequence of promises?](https://stackoverflow.com/questions/29880715/how-to-synchronize-a-sequence-of-promises) – Akrion Jun 12 '19 at 18:14

1 Answers1

0

Try using this package, which supports async/await in lodash https://www.npmjs.com/package/async-dash

Sarunya Durai
  • 181
  • 1
  • 2
  • 11