【发布时间】:2022-01-26 09:35:29
【问题描述】:
很容易忘记在异步函数中使用 try/catch,否则在使用 Promise 时无法捕获所有可能的错误。这可能会导致无休止的“等待”,因为 Promise 永远不会被解决也不会被拒绝。
如果存在未捕获的错误,是否有任何方法(例如通过代理或更改 Promise 构造函数)导致异步函数或其他 Promise 被拒绝?下面显示一个一般情况。我正在寻找某种方法来通过“等待”(如在抛出错误时应该拒绝“p”)而不修复“badPromise”。
async function badPromise() {
const p = new Promise((res) => {
delayTimer = setTimeout(() => {
console.log('running timeout code...');
if (1 > 0) throw new Error('This is NOT caught!'); // prevents the promise from ever resolving, but may log an error message to the console
res();
}, 1000);
});
return p;
}
(async () => {
try {
console.log('start async');
await badPromise();
console.log('Made it to the end'); // never get here
} catch (e) {
console.error('Caught the problem...', e); // never get here
}
})();```
【问题讨论】:
-
难道你不应该使用 Promise 的拒绝函数(res 之后的第二个参数)而不是 throw 吗?
-
不改变承诺就无法改变承诺...
标签: javascript promise uncaughtexceptionhandler