async.each 是非阻塞的吗? node.js

Is async.each non-blocking? node.js

我想用对象对数组进行非阻塞循环,所以我使用了async.each函数:

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

所以如果我 运行 上面的代码我有这样的消息输出:

before
inside
....
inside
end
after

如果 async.each 异步为什么我看不到那个顺序的输出?

before 
after
inside 
inside..
end 

更新 1: 谢谢答案,但是如果我想在我的路由器内执行该代码,我会阻止对我的服务器的所有响应吗?我需要改变什么?

async.each() 是异步的,但您没有做任何阻塞或需要异步循环的事情。如果你把 setTimeout() 放在那里你会看到它像你期望的那样工作。

在我看来,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]

为什么有意义?让我知道我是否可以进一步分解这些内容。