Home > Article > Web Front-end > How to Ensure Database Queries Finish Before Returning Results in a Loop with MongoDB and Q Promises?
Issue in Returning Retrieved Results from Database Queries Made in a Loop
In this query, the goal is to make multiple MongoDB queries in a loop and send the combined results as a single data array. However, using return within the loop does not wait for the database requests to complete, resulting in an undefined response. Even the use of Q.moulde does not resolve the issue.
Modified Code:
var getPrayerInCat = function(data){ var promises = data.map(function(data2){ var id = data2.id; return Q.nbind(Prayer.find, Prayer)({prayerCat:id}) .then(function(prayer) { if(!prayer) data2.prayersCount = 0; else data2.prayersCount = prayer.length; return data2; }) }); return Q.all(promises); }
Explanation:
The above is the detailed content of How to Ensure Database Queries Finish Before Returning Results in a Loop with MongoDB and Q Promises?. For more information, please follow other related articles on the PHP Chinese website!