我想用对象对数组进行非阻塞循环,所以我使用 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
UPDATE1: thx的答案,但如果我想在我的路由器中执行该代码,我将阻止所有响应我的服务器?我需要改变什么?
答案 0 :(得分:2)
对我来说,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]
为什么有意义?如果我能进一步打破这一点,请告诉我。
答案 1 :(得分:0)
async.each()是异步的,但您没有做任何阻塞或需要异步循环的事情。如果你在那里放一个setTimeout(),你会发现它像你期望的那样工作。