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

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

我不能完全弄清楚你是否可以调用一个具有callback的函数,并且在进入下一个函数之前等待callback函数。 另外,当API SDK需要callback时,是否将其命名为与async.waterfall中的callback名称相匹配(在本例中称为“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调用成功返回,则使用null作为第一个参数调用本地callback。 否则,用一个错误调用它, async.waterfall将停止执行并运行最终的callback。 例如(没有testingID):

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