Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Node.JS async.parallel

Tags:

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); 
like image 747
Maksim Dmitriev Avatar asked Nov 25 '13 06:11

Maksim Dmitriev


People also ask

What is async parallel in NodeJS?

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.

What is async series and async parallel in NodeJS?

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

What is the difference between async waterfall and async series?

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.


1 Answers

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' }); 
like image 94
Michael Tang Avatar answered Oct 22 '22 05:10

Michael Tang