Sunday, 9 April 2017

promises not executing sequentially javascript

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



via ali

No comments:

Post a Comment