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

查看:139
本文介绍了了解Node.JS async.parallel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从两个Web服务器请求数据。任务是独立的;因此,我正在使用 aync.parallel 。现在我只在我的网页正文中写'abc','xyz'和'Done'。

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\n');
        callback();
    }, function(callback) {
        res.write('x');
        res.write('y');
        res.write('z\n');
        callback();
    } ], function done(err, results) {
        if (err) {
            throw err;
        }
        res.end("\nDone!");
    });

}

var server = require('http').createServer(onRequest);
server.listen(9000);


推荐答案

如果您想在订单中绝对确定打印结果,你应该传递你的数据( abc \ n xyz \ n 回调(第一个参数是错误)并在最终的 async.parallel 回调的结果参数。

If you want to be absolutely certain in the order in which the results are printed, you should pass your data (abc\n and xyz\n) 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\n');
    },
    two: function(callback) {
        callback(null, 'xyz\n');
    }
}, function(err, results) {
    // results now equals to: results.one: 'abc\n', results.two: 'xyz\n'
});

这篇关于了解Node.JS async.parallel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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