简体   繁体   中英

async OR step in Node.js

I'm not able to get my asynchronous code working with node.js

Trying both async and step libraries -- the code only returns the first function (doesn't 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 THIS:

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

Step.js is expecting callbacks for each step. Also the function that is using Step should callback with the 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 Step would work like:

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 would get it to proceed through the steps.

Note that I personally prefer async for two reasons:

  • Step catches all thrown errors and does a callback with them; this changes the behavior of the application, when these libraries should just be cleaning up the look of the code.
  • Async has much better combination options and looks cleaner

I can only speak to async , but for that your anonymous functions in the array you pass to async.series must call the callback parameter that is passed into those functions when the function is done with its processing. As in:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM