async OR step in Node.js

2019-04-07 07:30发布

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

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-04-07 07:39

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
查看更多
别忘想泡老子
3楼-- · 2019-04-07 07:44

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();
    }
]);
查看更多
登录 后发表回答