简体   繁体   中英

Is async.each non-blocking? node.js

I want to make non-blocking loop over array with objects, so I used async.each function:

log.info("before");

async.each(products , function(prdt, callback){
    for(var i = 0 ; i <4000000000; i++){
        var s = i;
    }
    console.log("inside");
    callback();

}, function (err) {
    console.log("end");
});
log.info("after");

So if I run code above I have a such messages output:

before
inside
....
inside
end
after

If async.each asynchoronous why I dont see output in that order?

before 
after
inside 
inside..
end 

UPDATE1: thx for answers, but If I want to execute that code inside my router, I will blocked all responces to my server? What I need to change?

Seems to me that the async.each function is simply implying that it can be used for asynchronous actions because it inherently includes a callback function (which is trivial for you to add yourself in your own function).

Consider this code which uses Mongoose (a MongoDB wrapper) to simulate a real-world asynchronous call:

console.log("before");

async.each(["red", "green", "blue"], function(color, cb) {

    mongoose.model('products')
        .find({color: color})
        .exec(function(err, products) {
            if (err) return cb(err); // will call our cb() function with an error.
            console.log("inside");
            cb(null, products);
        });

}, function(err, products) {
    if (err) return console.error(err);
    console.log("really after");
    console.log(products);
});

console.log("after");

You'll get

before
after
inside
really after
[red products]
inside
really after
[green products]
inside
really after
[blue products]

Does it make sense why? Let me know if I can break any of this down further.

async.each() is asynchronous, but you're not doing anything that is blocking or requires an asynchronous loop. If you put a setTimeout() in there you'd see it working like you expect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM