理解 Node.JS async.parallel [英] Understanding Node.JS async.parallel

查看:25
本文介绍了理解 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 ) 通过 回调(第一个参数是错误) 并在最终的 async.parallel 回调的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆