簡體   English   中英

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 asynchoronous為什么我不按順序看到輸出?

before 
after
inside 
inside..
end 

更新1: thx的答案,但如果我想在我的路由器中執行該代碼,我將阻止所有響應我的服務器? 我需要改變什么?

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

這有道理嗎? 如果我能進一步打破這一點,請告訴我。

async.each()是異步的,但你沒有做任何阻塞或需要異步循環的事情。 如果你在那里放一個setTimeout(),你就會發現它像你期望的那樣工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM