gpt4 book ai didi

node.js - 当单个 promise 解决或拒绝时,如何让我的程序继续运行?

转载 作者:太空宇宙 更新时间:2023-11-04 03:00:02 26 4
gpt4 key购买 nike

我希望我的程序能够解决一切问题,然后使用 for 循环进行下一个测试;或者,如果出现错误,我希望它再次运行。但如果它遇到错误六次,我希望它放弃并尝试使用循环的下一个函数。

我的期望:

index is 0 and loop is 0
index is 1 and loop is 0
index is 2 and loop is 0
index is 3 and loop is 0
index is 4 and loop is 0
index is 5 and loop is 0
5 is too many errors
[printed error]
index is 0 and loop is 7
index is 1 and loop is 7
index is 2 and loop is 7
index is 3 and loop is 7
index is 4 and loop is 7
index is 5 and loop is 7
5 is too many errors
[printed error] .. and so on

我实际得到的是:

index is 0 and loop is 0
index is 1 and loop is 0
index is 2 and loop is 0
index is 3 and loop is 0
index is 4 and loop is 0
index is 5 and loop is 0
5 is too many errors
(node:29808) UnhandledPromiseRejectionWarning: undefined
(node:29808) UnhandledPromiseRejectionWarning: Unhandled promise rejection.

代码:

const hello = async (index, i) => {
return new Promise(async (resolve, reject) => {
console.log(`index is ${index} and loop is ${i}`)
if(index === 5){
reject(console.log(`${index} is too many errors`)) // this runs
} else if (index === 6){
resolve(console.log("I realize it won't ever resolve :) "))
}
else{
hello(++index, i)
}
})
};

const loop_function = async () => {
return new Promise (async(res, rej)=>{
for (var i = 0; i <= 35; i += 7) {
try{
await hello(0, i)
} catch(err){
console.log("caught an error!") // this does not run
}
}
res(console.log("resolved everything")) // this does not run
})
}


const final = async () =>{
await loop_function()
console.log("loop_function complete") // this does not run
}


final();

最佳答案

需要修改的内容:

  1. 从两个函数中清除new Promise()包装器;它们是不必要的,因为 AsyncFunctions 保证返回 Promise,并且在内部您可以简单地返回/抛出。
  2. 请务必返回 hello(++index, i),以便将每个递归级别的结果返回到其上级,并最终返回到最顶层的原始调用者。
  3. 当满足(index >= 5)条件时,只需抛出一个错误;无需记录,因为调用者的(loop_function's)catch block 将进行记录。

所以,你最终可能会得到:

const hello = async (index, i) => {
console.log(`index is ${index} and loop is ${i}`);
if(index >= 5) {
throw new Error(`${index} is too many errors`);
} else {
return hello(++index, i);
}
};
const loop_function = async () => {
for (var i = 0; i <= 35; i += 7) {
try {
await hello(0, i);
} catch(err) {
console.log(err.message);
}
}
console.log("resolved everything");
}
const final = async () =>{
await loop_function();
console.log("loop_function complete");
}
final();

关于node.js - 当单个 promise 解决或拒绝时,如何让我的程序继续运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60121299/

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