首页 > 解决方案 > 当单个承诺解决或拒绝时,我如何让我的程序继续运行?

问题描述

如果一切正常,我希望我的程序能够解决,然后使用 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();

标签: node.jspromiseasync-awaites6-promise

解决方案


需要修改的东西:

  1. 从两个函数中清除new Promise()包装器;它们是不必要的,因为 AsyncFunctions 保证返回 Promise 并且在内部你可以简单地返回/抛出。
  2. 确保return hello(++index, i)将递归的每个级别的结果返回到其上级,并最终返回到最顶层的原始调用者。
  3. (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();


推荐阅读