有关node.js中的async.waterfall的问题

时间:2015-03-27 19:17:57

标签: javascript node.js callback async.js

我对如何使用async.waterfall方法清理回调感到困惑。我有几个函数正在进行API调用,并通过回调从这些API调用返回结果。我想将结果从一个api调用传递给下一个。我还希望将这些调用封装在单独的函数中,而不是将它们直接粘贴到async.waterfall控制流中(为了便于阅读)。

我无法弄清楚你是否可以调用一个具有回调功能的函数,它会在转到下一个函数之前等待回调。此外,当API SDK需要回调时,我是否将其命名为与async.waterfall中的回调名称匹配(在本例中称为“回调”)?

我可能会把很多东西混在一起。希望有人可以帮我解开这个问题。下面是我正在尝试做的部分代码片段......

async.waterfall([
  function(callback){
    executeApiCallOne();
    callback(null, res);
  },
  function(resFromCallOne, callback){
    executeApiCallTwo(resFromCallOne.id);
    callback(null, res);
  }],
  function (err, res) {
    if(err) {
        console.log('There was an error: ' + err);
    } else {
        console.log('All calls finished successfully: ' + res);
    }
  }
);

//API call one
var executeApiCallOne = function () {

    var params = {
      "param1" : "some_data",
      "param2": "some_data"
      };

    var apiClient = require('fakeApiLib');
    return apiClient.Job.create(params, callback);
    // normally I'd have some callback code in here
    // and on success in that callback, it would
    // call executeApiCallTwo
    // but it's getting messy chaining these
};

//API call two
var executeApiCallTwo = function (id) {

    var params = {
      "param1" : "some_data",
      "param2": "some_data",
      "id": id
      };

    var apiClient = require('fakeApiLib');
    // do I name the callback 'callback' to match
    // in the async.waterfall function?
    // or, how do I execute the callback on this call?
    return apiClient.Job.list(params, callback);
};

1 个答案:

答案 0 :(得分:3)

如果您的某个api调用成功返回,则使用null作为第一个参数调用本地回调。否则,请调用它并显示错误,async.waterfall将停止执行并运行最终回调。例如(没有测试id):

async.waterfall([
  function(callback){
    executeApiCallOne(callback);
  },
  function(resFromCallOne, callback){
    executeApiCallTwo(resFromCallOne.id, callback);
  }],
  function (err, res) {
    if(err) {
        console.log('There was an error: ' + err);
    } else {
        // res should be "result of second call"
        console.log('All calls finished successfully: ' + res);
    }
  }
);

//API call one
var executeApiCallOne = function (done) {

var params = {
  "param1" : "some_data",
  "param2": "some_data"
  };

var apiClient = require('fakeApiLib');
    return apiClient.Job.create(params, function () {
        // if ok call done(null, "result of first call");
        // otherwise call done("some error")
    });
};

//API call two
var executeApiCallTwo = function (id, done) {

    var params = {
      "param1" : "some_data",
      "param2": "some_data",
      "id": id
      };

    var apiClient = require('fakeApiLib');
    // do I name the callback 'callback' to match
    // in the async.waterfall function?
    // or, how do I execute the callback on this call?
    return apiClient.Job.list(params, function () {
        // if ok call done(null, "result of second call");
        // otherwise call done("some error")
    });
};