Understanding Node.JS async.parallel

2019-01-21 17:23发布

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

The code.

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);

1条回答
Evening l夕情丶
2楼-- · 2019-01-21 17:44

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'
});
查看更多
登录 后发表回答