为什么通过try / catch我的代码会收到Node.js的其他错误消息?

我在异步函数内部使用try / catch块,但Node.js收到一些其他错误消息。我的代码:

const work = count => {
    const promise = new Promise((resolve,reject) => {
        const interval = setInterval(() => {
            console.log(count--);
            if(!count){
                try{
                    clearInterval(interval);
                    throw 'Oops...'; // emulate unexpected error...
                    resolve('Work done!');
                }
                catch(err){
                    reject(err);
                }
            }
        },1000);
        console.log('Bingo!');
    });
    return promise;
};

const promise = work(3);
promise.then(context => console.log(`Ressult: ${context}`));
promise.catch(err => console.log(`Error: ${err}`));

结果:

为什么通过try / catch我的代码会收到Node.js的其他错误消息?

我做错了什么?

a728281971 回答:为什么通过try / catch我的代码会收到Node.js的其他错误消息?

您需要按以下方式更新代码:您未处理拒绝的承诺,因为.then返回的新承诺在您的情况下是错误的承诺。

    const work = count => {
    const promise = new Promise((resolve,reject) => {
        const interval = setInterval(() => {
            console.log(count--);
            if(!count){
                try{
                    clearInterval(interval);
                    throw 'Oops...'; // emulate unexpected error...
                    resolve('Work done!');
                }
                catch(err){
                    reject(err);
                }
            }
        },1000);
        console.log('Bingo!');
    });
    return promise;
};
const promise = work(3);
promise.then(context => console.log(`Ressult: ${context}`)).catch(err => console.log(`Error: ${err}`));
本文链接:https://www.f2er.com/3168145.html

大家都在问