26

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);
2
  • 1
    The order of what is written to res is dependant on which of the async.parallel task finishes first but as the tasks are independent than the order shouldn't matter.
    – Bulkan
    Commented Nov 25, 2013 at 6:45
  • @Bulkan, thank you. But parallel seems not to work properly. Please read a new question. Commented Nov 25, 2013 at 7:23

1 Answer 1

59

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'
});
4
  • I can pass the arguments, but I should perform long operations within the parallel functions Commented Nov 25, 2013 at 10:40
  • I was assuming you were doing some long operation to get the two strings (maybe from a database), suggesting separating the code for retrieving data (parallel) and processing (res.write) it (sequential). Commented Nov 25, 2013 at 20:36
  • Strange conversation you have here, guys. Did Michael Tang gave correct answer? Not clear
    – Green
    Commented Jan 21, 2017 at 4:45
  • @Green I think some of the comments were lost... basically what I meant was that the writing of the data to the console is something one wants to be synchronized, and thus should be executed in the parallel's callback. The functions in the first argument to parallel should be in charge of getting any data (that can be done asynchronously in any order) and collecting it for parallel's callback. In this case we're calling parallel with trivial functions, but one can imagine reading from disk or the network in its place. Commented Jan 21, 2017 at 8:04

Not the answer you're looking for? Browse other questions tagged or ask your own question.