Is async.each non-blocking? node.js

I want to make a non-blocking loop over an array with objects, so I used the 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 the code above, I have this output:

before
inside
....
inside
end
after

If async.each is asynchoronous, why can't I see the output in this order?

before 
after
inside 
inside..
end 

Update1: thanks for the answers, but if I want to execute this code inside my router, will I block all the answers on my server? What do i need to change?

+4
source share
2 answers

, async.each , , ( , ).

, Mongoose ( MongoDB) :

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");

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

, ? , .

+2

async.each() , , . setTimeout() , , , .

0

Source: https://habr.com/ru/post/1598977/


All Articles