gpt4 book ai didi

javascript - node.js:如何使用序列和 promise 来模拟两个异步循环

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

我在 node.js 中有两个函数,我们称它们为 func_A 和 func_B,它们每个都需要在循环中调用,但需要一个接一个地调用。

首先,func_a需要循环调用num1次。

for (i=0; i<num1; i++)
{
func_a(i, function(err,cb1))
}

当上面完成后,func_b需要循环调用num2次

for (j=0; j<num2; j++)
{
func_b(j, function(err,cb2))
}

当上述所有 aync 函数调用完成并返回时,我需要对两个 cb 结果执行其他操作。我可以使用 hell 般的回调金字塔来完成上述操作,并使用计数器来跟踪回调完成情况。但是我想使用 sequence 和 promise 来简化我的代码。我该怎么做呢?我不太清楚如何使用循环调用的函数来完成它。

最佳答案

在制作了func_a()func_b() 的promisified 版本后,您可以使用Promise.all()await async function 中的聚合结果不使用计数器:

const promisify = fn => function () {
return new Promise((resolve, reject) => {
// forward context and arguments of call
fn.call(this, ...arguments, (error, result) => {
if (error) {
reject(error)
} else {
resolve(result)
}
})
})
}

const func_a_promisified = promisify(func_a)
const func_b_promisified = promisify(func_b)

async function loop_a_b (num1, num2) {
// await pauses execution until all asynchronous callbacks have been invoked
const results_a = await Promise.all(
Array.from(Array(num1).keys()).map(i => func_a_promisified(i))
)

const results_b = await Promise.all(
Array.from(Array(num2).keys()).map(j => func_b_promisified(j))
)

return {
a: results_a,
b: results_b
}
}

// usage
loop_a_b(3, 4).then(({ a, b }) => {
// iff no errors encountered
// a contains 3 results in order of i [0..2]
// b contains 4 results in order of j [0..3]
}).catch(error => {
// error is first encountered error in chronological order of callback results
})

为了简化 Array.from(...).map(...) 困惑,您可以编写一个助手 generator function并发调用异步函数:

function * loop_fn_n (fn, n) {
for (let i = 0; i < n; i++) {
yield fn(n)
}
}

然后将loop_a_b改为:

async function loop_a_b (num1, num2) {
// await pauses execution until all asynchronous callbacks have been invoked
const results_a = await Promise.all(
loop_fn_n(func_a_promisified, num1)
)

const results_b = await Promise.all(
loop_fn_n(func_b_promisified, num2)
)

return {
a: results_a,
b: results_b
}
}

作为@OleksiiTrekhleb指出,我在这里实现的 promisify 函数在 Node.js 核心模块中也可用 util .

关于javascript - node.js:如何使用序列和 promise 来模拟两个异步循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52596082/

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