Maxiss
Maxiss

Reputation: 1056

How to modify one array item with an asynchronous call

I would like to use an await in a loop to modify a function but figured out that as the call I make in the foreach loop is asynchronous, it doesn't work as expected and my table ends up being empty. So i think the good choice would be to use map instead but I don't manage to make it work as expected:

   optionsRaw.forEach(async raw => {
      const option = new Option();
      option.id = raw['id'];
      option.nbMax = raw['nb_max'];
      option.disabled = (await this.countAnswer(option.id))>=option.nbMax;

      options.push(option);
    });

    return options;

Options is empty when I have this await Can I just add a 'then' or something?

Otherwise, can I do it like this:

options = options.map(async option=>{
  option.disabled = option.nbMax>0 && (await this.countAnswer(option.id, id_challenge))>=option.nbMax;
  return option;
})
return options;

"Type promise is not assignable to type Option[]"

But no success for now, I think I definitely miss something with this 'map'

Upvotes: 0

Views: 506

Answers (1)

Pylon
Pylon

Reputation: 768

You need to use Promise.all, it returns a new promise which is fulfilled with an array of fulfillment values for the passed promises or rejects with the reason of the first passed promise that rejects. we could see MDN doc here.

So, wrapped your code with Promise.all like this,

options = Promise.all(options.map(async option=>{
    option.disabled = option.nbMax>0 && (await this.countAnswer(option.id, id_challenge))>=option.nbMax;
    return option;
  }));
return options;

Upvotes: 1

Related Questions