非同期関数で try/catch を使用することを忘れたり、promise を操作するときに考えられるすべてのエラーをキャッチできなかったりすることはよくあります。これにより、無限の「待機」が発生する可能性があり、Promise が解決または拒否されることはありません。
キャッチされていないエラーがある場合に非同期関数またはその他の約束を拒否する方法はありますか (プロキシ経由または約束コンストラクターの変更など)。以下は、一般化されたケースを示しています。「badPromise」を修正せずに「await」を通過する方法を探しています(エラーがスローされたときに「p」を拒否する必要があるため)。
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
}
})();```