gpt4 book ai didi

javascript - Node async.js 多重功能与 waterfall

转载 作者:行者123 更新时间:2023-11-30 08:34:26 25 4
gpt4 key购买 nike

我不是 node 和 async.js 方面的专家。所以期待 node js 社区的帮助。所以这是我的场景,我想一个接一个地做 3 个操作,每个都取决于之前的结果。通过使用以前的结果,我需要调用异步函数来检索另一个结果。所以我决定使用异步 waterfall 。 (希望我选择了正确的)。

async.waterfall([
function(callback) {
request({
method: 'GET',
headers: {'Content-Type' : 'application/json'},
url : url
},function(error, response, body){
if(error) {
callback(error);
} else {
var result= JSON.parse(body);
callback(null,result); //sending to next function
}
});
},
function(result, callback) {
//here i want to use the result array in loop async.eachSeries or forEachSeries and fetch another result array using request module then send it to next function
/*Here I don't know How to process the result*/
callback(null,result1)
},
function(result1, callback) {
//here i want to use the result1 array and fetch another result array then send it to next function
callback(null,result2)
}
], function(error, res) {
console.log(res); // process final result
});

我引用了一些教程。我无法理解这就是为什么最终会出现在 SO 中的原因。提前致谢。

最佳答案

只需在 waterfall 函数系列中的每个函数上使用传入的每个 cb。

顺便说一句,我不得不说:

  1. 不要嵌套异步函数
  2. 尝试改用 promises
  3. 经常检查整个异步模块功能,很多时候,有些东西可以并行运行

好的,那么对于waterfall函数,基本上需要如下语法,语义上:

async.waterfall(arrayOfFunctions, [optionalResolveCallbackFunction]);

函数数组中的第一个元素具有以下语法:

function (cb) {...};

以下 n 个函数将需要以下语法:

function (param1, param2, ... paramN, cb){...}

因此,最后一个参数将是用于转到下一个函数或返回错误的参数。 waterfall params 的数量是可选的。

每个cb 函数都遵循错误回调 约定,其中错误是要传递的第一个参数。如果数组中的任何函数返回错误,执行将被中断,代码将转到最后一个 optionalResolveCallbackFunction

所以,再一次,当您决定终止循环 async.eachSeries 或 forEachSeries 时,即使那样会产生复杂的代码(甚至容易出现性能问题的风险),您将使用回调 恰好是 waterfall 函数的回调参数的对象,用于传递给后续函数或结束执行。

关于javascript - Node async.js 多重功能与 waterfall ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33173517/

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