我正在使用async-await,并在引发错误时通过try-catch处理错误。method3()未被method1()捕获。但是,如果我删除了异步。 method2()foreach我能够捕获method1()中的错误!但是,如果我在foreach中删除异步操作,则无法使用await,因此无法使用await!有没有办法解决这个问题
class A {
async method1(A, B) {
return new Promise(async (resolve, reject) => {
try {
await this.method2(A, B);
} catch (error) {
console.log(error, "error")
};
});
}
async method2(A, B, C) {
await somethingelsecalled();
Array.forEach(async (segment, index) => {
result = await somethingcalled()
this.method3(result);
});
}
method3() {
throw "error";
}
}
用for循环替换foreach解决了问题
class A {
async method1(A, B) {
return new Promise(async (resolve, reject) => {
try {
await this.method2(A, B);
} catch (error) {
console.log(error, "error")
};
});
}
async method2(A, B, C) {
await somethingelsecalled();
for (const [index, segment] of Array.entries()) {
result = await somethingcalled()
this.method3(result);
});
}
method3() {
throw "error";
}
}