Hello I am continuing to learn promises and am struggling with how to correctly use Promise.All or whether or not I should be using it in this situation.
I am connecting to a data source and resolving my first promise to an array. After that I want to take those results and with another promise loop through the results and add another value to the array which is using an external API call.
After research it sounded like I needed to use Promise.All so that the promises would be completed before returning my response but I am still getting a status of pending on the value that I am adding to my array instead of the expected value. Again I am just learning node and promises so my approach might be completely flawed and in that case I am open to any suggestions on a better way to do what I am attempting to accomplish.
function GetSearches(req, res) {
var BingSearches = new Promise((resolve, reject) => {
GetBingSearches().toArray((err, response)=>{
resolve(response);
});
}) /* get data from external data source example data: [{SearchTerm: "Boxing", id: '4c142f92-ba6d-46af-8dba-cb88ebabb94a', CreateDate: '2017-08-10T13:59:20.534-04:00'}] */
var GetSearchesWithImageUrl = BingSearches.then((response,reject) =>{
for(var i in response){
response[i].Image = new Promise((resolve, reject) => {
Bing.images(response[i].SearchTerm, {
count: 1
}, (err,res,body) => {
const bingImageUrl = body.value[0].contentUrl;
console.log(bingImageUrl) // bing image url link
resolve(bingImageUrl);
});
});
} // loop through array and add value
return response;
}).catch((err) => {
console.log(err);
})
return Promise.all([BingSearches ,GetSearchesWithImageUrl ]).then(([BingSearches , GetSearchesWithImageUrl ]) => {
console.log(GetSearchesWithImageUrl )
/* my response is now [{SearchTerm: "Boxing", id: '4c142f92-ba6d-46af-8dba-cb88ebabb94a', CreateDate: '2017-08-10T13:59:20.534-04:00', Image: Promise { pending } }] */
res.status(200).json(GetSearchesWithImageUrl )
}).catch((err) => {
console.log(err);
})
}
I was hoping that Promise.All would wait for all my promises to complete but I do not seem to understand how it works. I am open to any advice/explanation of what I am doing wrong.
Thanks!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…