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);
Asynchronous operations in parallel The first argument to async. parallel() is a collection of the asynchronous functions to run (an array, object or other iterable). Each function is passed a callback(err, result) which it must call on completion with an error err (which can be null ) and an optional results value.
async. series invokes your functions serially (waiting for each preceding one to finish before starting next). async. parallel will launch them all simultaneously (or whatever passes for simultaneous in one-thread land, anyway).
waterfall allows each function to pass on its results to the next function, while async. series passes all the task's results to the final callback. The async. waterfall() will pass only the result of the last function called to the main callback.
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' });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With