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

questions about async.waterfall in node.js

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

我不太清楚你是否可以调用一个有回调的函数,它会在进入下一个函数之前等待回调,或者不。此外,当 API SDK 需要回调时,我是否将其命名为与 async.waterfall 中的回调名称匹配(在本例中称为 'callback')?

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

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

如果您的 api 中的一个调用 returns 成功,您将使用 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")
    });
};