Reputation: 65
I have the piece of code below executing using promises.The problem I have is that the promise is not executing sequentially by waiting for the first block to execute before proceeding to the next block
below is the code:
array[]
new Promise(function(resolve, reject) {
//userarray is some array with user id's
userarray.forEach(function(entry) {
User.findOne({ user_id: entry}, function(err, user) {
if (err) throw err;
console.log(user.name);
array.push(user.name);
});
});
resolve("success");
})
.then(function() {
console.log(array);
console.log("done");
});
below is the output
[] //array is still empty
done
tom
dick
harry
when what i want is
tom
dick
harry
["tom", "dick", "harry"]
done
Upvotes: 1
Views: 110
Reputation: 12778
It seems like User.findOne
will call its callback asynchronously so that your promise is resolved before the callbacks are actually invoked. You can try something like this:
var promises = userarray.map(function(entry) {
return new Promise(function(resolve, reject) {
User.findOne({ user_id: entry}, function(err, user) {
if (err) reject(err);
console.log(user.name);
resolve(user.name);
});
});
});
Promise.all(promises).then(function(array) {
console.log(array);
console.log("done");
});
Upvotes: 4
Reputation: 1694
This solution is not really elegant but should get the job done.
var length = userarray.length;
userarray.forEach(function(entry) {
User.findOne({ user_id: entry}, function(err, user) {
if (err) throw err;
console.log(user.name);
array.push(user.name);
if(!--length) resolve("success");
});
});
})
Upvotes: 0