Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
');
        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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
221 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...