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));
mapis totally fine to map an array of values to an array of promises. There's nothing wrong with the usage ofmapandPromise.allin the above snippetthen()takes a callback function, but you callres.status(200).send(articles)immediately (and pass its result,undefined, tothen). Wrap it in a function expression.