我希望能夠從承諾的功能之外捕捉到承諾內拋出的異常。請看下面的代碼:如何捕捉內部異常?
throwError =() => {
throw new Error("myError");
};
let iWantToCatchTheErrorThatThisOneThrows =() => {
return (new Promise((resolve) => {
resolve()
}).then(() => {
(new Promise((resolve, reject) => {
return throwError();
}));
return new Promise((resolve) => setTimeout(resolve, 1000));
})).catch((error) => {
//Never reaches here
console.log(error)
});
};
iWantToCatchTheErrorThatThisOneThrows().then(() => {
console.log("Quit gracefully");
}).catch((error) => {
//Never reaches here
console.log(error);
});
我能趕上內部錯誤,但我不能把它結束了,我想(到底),通過在中間增加一個問題:
let iWantToCatchTheErrorThatThisOneThrows =() => {
return (new Promise((resolve) => {
resolve()
}).then(() => {
(new Promise((resolve, reject) => {
return throwError();
})).catch((error) => {
//Prints, but thrown error isn't bubbled anywhere
console.log(error);
throw new Error(error);
});
return new Promise((resolve) => setTimeout(resolve, 1000));
})).catch((error) => {
//Never reaches here
console.log(error)
});
};
iWantToCatchTheErrorThatThisOneThrows().then(() => {
console.log("Quit gracefully");
}).catch((error) => {
//Never reaches here
console.log(error);
});
所有測試中7.1.0的NodeJS是運行
在內部回調中,您會進行各種投擲和重新投擲,然後返回一個無關的,已解決的承諾。毫不奇怪,外層的'.catch()'沒有什麼可抓的。 –