node.js - 当单个承诺解决或拒绝时,我如何让我的程序继续运行?
问题描述
如果一切正常,我希望我的程序能够解决,然后使用 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();
解决方案
需要修改的东西:
- 从两个函数中清除
new Promise()
包装器;它们是不必要的,因为 AsyncFunctions 保证返回 Promise 并且在内部你可以简单地返回/抛出。 - 确保
return hello(++index, i)
将递归的每个级别的结果返回到其上级,并最终返回到最顶层的原始调用者。 - 当
(index >= 5)
条件满足时,简单地抛出一个错误;无需记录,因为调用者的 (loop_function's)catch
块将进行记录。
因此,您最终可能会得到:
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();
推荐阅读
- c++ - 在 C++ 类成员函数上使用#ifdef 保护是否安全?
- angularjs - 为什么 AngularJS Counter 在没有初始化的情况下仍然可以工作?
- django - 覆盖具有相同名称的模板是 django
- reactjs - onclick 事件的三元条件
- gdb - 在使用 ddd(显示调试器)时,如何在导航后返回到源代码行中停止执行的位置?
- r - uniqueN 返回错误结果,条件为 j
- sql - 满足条件时如何返回所有行但更改计数-postgresql
- python - Socket 无法读取大文件。Python
- azure - Azure DevOps 在 Excel 中以树级别提取工作项
- c++ - 如何将 .o 文件输出到一个特定的文件夹中?