gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 00:42:39 25 4
gpt4 key购买 nike

我对如何使用 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);
};

最佳答案

如果您的一个 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")
});
};

关于javascript - 关于 node.js 中 async.waterfall 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29308573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com