Async OR step in Node.js

I can not get my asynchronous code working with node.js

An attempt of both asynchronous and step libraries - the code returns only the first function (it does not seem to go through the rest). What am I doing wrong?

thanks!

var step = require('step'); step( function f1(){ console.log('test1'); }, function f2(){ console.log('test2'); }, function finalize(err) { if (err) { console.log(err);return;} console.log('done with no problem'); } ); 

or that:

 var async = require('async'); async.series([ function f1(){ console.log('test1'); }, function f2(){ console.log('test2'); }, function finalize(err) { if (err) { console.log(err);return;} console.log('done with no problem'); } ]); 
+7
source share
2 answers

Step.js expects callbacks for each step. Also, a function using Step should return a result and not return it.

So let's say you have:

 function pullData(id, callback){ dataSource.retrieve(id, function(err, data){ if(err) callback(err); else callback(data); }); } 

Using the step will work as follows:

 var step = require('step'); function getDataFromTwoSources(callback){ var data1, data2; step( function pullData1(){ console.log('test1'); pullData(1, this); }, function pullData2(err, data){ if(err) throw err; data1 = data; console.log('test2'); pullData(2, this); }, function finalize(err, data) { if(err) callback(err); else { data2 = data; var finalList = [data1, data2]; console.log('done with no problem'); callback(null, finalList); } } ); }; 

This will make him follow the steps.

Please note that I personally prefer asynchronous operation for two reasons:

  • The step catches all abandoned errors and calls back with them; this changes the behavior of the application when these libraries just need to clear the look of the code.
  • Async has much better combination options and looks cleaner.
+3
source

I can only speak with async , but for this, your anonymous functions in the array that you pass to async.series should call the callback parameter, which is passed to these functions when the function is processed. How in:

 async.series([ function(callback){ console.log('test1'); callback(); }, function(callback){ console.log('test2'); callback(); } ]); 
+2
source

All Articles