0

In the code provided below, I would like to modify the 'image' field of each object (article) stored in the 'articles' array. I know that I can create an empty array and push a deep copy of each article one by one using the spread operator as described here. Is there any way I can change the contents of the array 'in place'? I have tried passing articles as a third argument, and I'm still not able to modify the 'image' field of each article stored in the array. Thanks in advance.

let requests = articles.map((article, i)=>{
     return new Promise((resolve) => {
          articleImage.findById(article.image, (err, theImage)=>{
               if(err) return res.status(400).send(err);
               articles[i].image = theImage.source;
               resolve();
          });
     });
});
Promise.all(requests).then(res.status(200).send(articles));
5
  • 2
    First of all map is sync and promise is async! They cannot be coupled together. Your data is processed after promise is resolved. So you cannot do async operations in synchronous loops i.e. for, forEach, map, etc Commented Aug 25, 2018 at 8:21
  • 2
    @MeetZaveri map is totally fine to map an array of values to an array of promises. There's nothing wrong with the usage of map and Promise.all in the above snippet Commented Aug 25, 2018 at 12:55
  • 2
    Your problem is that then() takes a callback function, but you call res.status(200).send(articles) immediately (and pass its result, undefined, to then). Wrap it in a function expression. Commented Aug 25, 2018 at 12:56
  • @Bergi I decided to modify each article in the array, then resolve each promise with each modified article, and then wrap the response in a function, as you suggested, with 'requests' as argument. It's not technically modifying the articles in place, but at the very least I'm not manually creating an array and pushing stuff to it. Thanks for the response. Commented Aug 25, 2018 at 23:54
  • 2
    @MeetZaveri I don't see why using a map to synchronously create an array of Promises that will then resolve/reject as part of the array at a later time could cause any inconsistencies. Could you share some instances where mapping promises into an array could cause inconsistencies? In this situation, it wasn't that causing the problem. Commented Aug 25, 2018 at 23:59

0

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.