I am trying to run some database queries (using sails.js) on an array and upon the queries' return, do something. I figured the best way to do so would be to use a for loop and resolve the promises async, and once they've all resolved, continue on. However, only the last promise in my array is resolving, and it is resolving multiple times because in each 'User.findOne...' then function, the index is array.length-1.
My questions:
- How does variable scope in asynchronous loops work? Best resources to explain this?
- What is the best way to solve my problem? Why?
- Are there any other patterns I should use or not use? I am fairly new to promises and async js, so any tips would be helpful!
Main tutorials I've checked
- https://github.com/kriskowal/q
- https://github.com/kriskowal/q/wiki/API-Reference
- https://github.com/bellbind/using-promise-q/
Thank you for your help!
My simplified code:
functionWhichReturnsPromise()
.then(function(user){
var promises = [];
Q.try(function(){
for (var index in array) {
var fbid = array[index];// Get fbid from array
promises.push(Q.defer().promise); // Add promise to promise array
// Find userid from fbid; resolve respective promise when finished
User.findOne({facebook_id: fbid}).then(function(userSeen){
promises[index].resolve(userSeen.id);
sails.log('resolved where id=' + userSeen.id); // correct
sails.log('resolved where index=' + index); // PROBLEM: always last index
});
}
}).then(function(){
// For debugging purposes
Q.delay(1000).then(function(){
sails.log(promises[0]); // Unresolved
sails.log(promises[1]); // Unresolved
sails.log(promises[2]); // Only last promise in array is resolved
});
// When the userids have been extracted from above (promises fulfilled)...
Q.all(promises).then(function(seenids){
// Do stuff here (Doesn't get here)
});
});
});