3

非同期関数で 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
    }
})();```

4

4 に答える 4

0

rejectこれを行う方法があるかもしれませんが、あなたの場合、 Promise の代わりに関数を本当に使いたいと思いますthrow。それが本当に拒否の目的です。

async function badPromise() {
    const p = new Promise((res, reject) => {
        delayTimer = setTimeout(() => {
            console.log('running timeout code...');
            if (1 > 0) {
              reject('This is NOT caught!');
              return;
            }
            res();
        }, 1000);
    });
    return p;
}

(async () => {
    try {
        console.log('start async');
        await badPromise();
        console.log('Made it to the end'); // never gets here
    } catch (e) {
        console.error('Caught the problem...', e); // should work now
    }
})();
于 2022-01-25T22:42:43.547 に答える