shamon shamsudeen
shamon shamsudeen

Reputation: 5848

modify array after promise.all in foreach loop

I have an array like this

 let result =  [{id:1,name:'test',dealValue:'ds',dealType:2},{id:2,name:'test1',dealValue:'ds',dealType:4}];

I am looping the above array to call another function which is also a promise after each iteration I need to add the value as a new item in the current array.

let temp = [];

result.forEach((element, index) => {
    //build the promise    
    temp.push(getAmount(element.dealValue, element.dealType));
  });
  //execute array of promise
  let r = await Promise.all(temp);
  //add new key value pair
  result.forEach((element, index) => {
    element.IDGfee = r[index];
  });

This works fine, however, I am running two foreach loops to achieve my desired result ,is there any better way to do this??

Upvotes: 0

Views: 96

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370779

You could use .map instead, and assign back to element inside a .then chained onto the getAmount call:

await Promise.all(
  result.map((element) => (
    getAmount(element.dealValue, element.dealType)
      .then((result) => {
         element.IDGfee = result;
      })
  ))
);

(Though, as comment notes, this will not wait for every response to come back before assigning to each element - your current code will throw before assigning if any request throws an error, whereas this may well throw after some properties have been assigned to.)

Upvotes: 1

Related Questions