Javascript/NodeJS: Array empty after pushing values in forEach loop

问题内容:

I got a little bit of a problem. Here is the code:

Situation A:

var foundRiders = [];

            riders.forEach(function(rider){
                Rider.findOne({_id: rider}, function(err, foundRider){
                    if(err){
                        console.log("program tried to look up rider for the forEach loop finalizing the results, but could not find");
                    } else {
                        foundRiders.push(foundRider);
                        console.log(foundRiders);
                    }
                });
            });

Situation B

var foundRiders = [];

            riders.forEach(function(rider){
                Rider.findOne({_id: rider}, function(err, foundRider){ 
                    if(err){
                        console.log("program tried to look up rider for the forEach loop finalizing the results, but could not find");
                    } else {
                        foundRiders.push(foundRider);
                    }
                });
            });
            console.log(foundRiders);

So in Situation A when I console log I get that foundRiders is an array filled with objects. In situation B when I put the console.log outside the loop, my roundRiders array is completely empty…

How come?

问题评论:

1  
it’s async, your console.log gets called before the query is finished. That’s why you are passing your callback function
    
console.log(foundRiders); is executed before the Rider.findOne is fineshed executing as it is asynchronous.
    
…….because why not ! and also nodejs is asynchronous
    
How do I delay it? I’m coming form PHP and this Asynchronous programming takes some time to get a hang of.
– RutgerBrns
3 mins ago

原文地址:

https://stackoverflow.com/questions/47756209/javascript-nodejs-array-empty-after-pushing-values-in-foreach-loop

Add a Comment