0

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??

1
  • Array items are a little bit different than the original apart from that everything is used Commented Feb 19, 2019 at 9:04

1 Answer 1

1

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

The behaviour in your code and the OP code might be different depending upon what the OP wants to do incase any one call fails.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.