理解 Node.JS async.parallel [英] Understanding Node.JS async.parallel
问题描述
我需要从两个 Web 服务器请求数据.任务是独立的;因此,我使用 aync.parallel.现在我只在我的网页正文中写入abc"、xyz"和完成".
I need to request data from two web servers. The tasks are independent; therefore, I am using aync.parallel. Now I am only writing 'abc', 'xyz', and 'Done' to the body of my web page.
由于任务是同时执行的,我会遇到奇怪的输出吗?例如,
Since tasks are performed at the same time, can I run into a strange output? E.g.,
xab
cyz
代码.
var async = require('async');
function onRequest(req, res) {
res.writeHead(200, {
"Content-Type" : "text/plain"
});
async.parallel([ function(callback) {
res.write('a');
res.write('b');
res.write('c
');
callback();
}, function(callback) {
res.write('x');
res.write('y');
res.write('z
');
callback();
} ], function done(err, results) {
if (err) {
throw err;
}
res.end("
Done!");
});
}
var server = require('http').createServer(onRequest);
server.listen(9000);
推荐答案
如果你想绝对确定打印结果的顺序,你应该传递你的数据 (abc
和 xyz
) 通过 回调(第一个参数是错误) 并在最终的 results
参数中处理/写入它们.
If you want to be absolutely certain in the order in which the results are printed, you should pass your data (abc
and xyz
) through the callbacks (first parameter is the error) and handle/write them in the final async.parallel
callback's results
argument.
async.parallel({
one: function(callback) {
callback(null, 'abc
');
},
two: function(callback) {
callback(null, 'xyz
');
}
}, function(err, results) {
// results now equals to: results.one: 'abc
', results.two: 'xyz
'
});
这篇关于理解 Node.JS async.parallel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!