是async.each非阻塞? 的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
UPDATE1:THX的答案,但如果我想在我的路由器执行该代码,我会阻止所有的响应我的服务器? 我需要改变什么?
在我看来, async.each
函数只是意味着它可以用于asynchronous操作,因为它本质上包含了一个callback函数(对于您自己添加到自己的函数中是微不足道的)。
考虑使用Mongoose(一个MongoDB包装器)来模拟真实世界asynchronous调用的代码:
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()是asynchronous的,但是你没有做任何阻塞或需要asynchronous循环的东西。 如果你把一个setTimeout()放在那里,你会看到它像你期望的那样工作。
- 将parameter passing给async.js任务
- 节点MySQL以最快的速度执行多个查询
- node.js async.js nextTick vs setImmediate
- 每个简单的asynchronouseachLimit示例会引发范围错误?
- 使用async.js进行asynchronous树遍历
- 我如何pipe理Node.jsasynchronousvariables作用域?
- Nodejsasynchronous编程 – 为什么需要“asynchronous”模块? 什么是“回拨地狱”/“厄运金字塔”?
- node.jsasynchronous串行函数的参数
- 如何使用async.js中的Promise进行编码?