首页 > 解决方案 > unhandledRejection nodejs

问题描述

我知道有很多关于此错误的帖子,其中大多数都有相同的答案,但不知何故我仍然收到警告。

我在 Node.js 7 中读过类似的内容,抑制 UnhandledPromiseRejectionWarning 的正确方法是什么?但是由于事件侦听器泄漏而不是on我使用once,但有时我仍然会看到警告

我确实想摆脱警告或解决它,因为它的说法将来会被弃用,但不确定何时。

起初,当我第一次跑步时,我会先得到这个

You have triggered an unhandledRejection, you may have forgotten to catch a Promise rejection: myrejectionmessage

然后,我会收到这个错误

UnhandledPromiseRejectionWarning: myrejectionmessage UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 5)

这是我的原始代码,没有我尝试过的帖子,我正在尝试获取一些文件,aws s3 bucket但存储桶中的文件可能不存在

这个功能是比较是否有文件然后比较修改时间,如果文件不存在reject

exports.compareObjectMT = (s3, Key, getFileStat) => {
    const s3GetParams = {
        Bucket: process.env.S3_BUCKET,
        Key,
    };

    return new Promise((res, rej) => {
        s3.getObject(s3GetParams, (err, data) => {
            if (err) rej('myrejecterror');
            if (data) {
                res(String(getFileStat.mtimeMs) === data.Metadata.mtimems);
            }
            res(false);
        });
    });
};

在此先感谢您的任何建议

这就是我使用该功能的方式

exports.s3Put = async (path) => {
    try {
        fs.readFile(path, async (err, fileBinary) => {
            if (err) throw err;
            // console.log(data, 'data');
            const s3 = new AWS.S3();
            const Key = path.replace(process.env.WATCH_PATH, '');
            const getStat = await getFileStat(path);
            console.log(getStat, 'getstateeeeeeeeeeeeeeee');
            const compareObj = await compareObjectMT(s3, Key, getStat);
            console.log(compareObj, 'compareObj');
        });
    } catch (e) {
        console.log(e, 'errorrrrrrrrrrrrr');
    }
};

标签: javascriptnode.jserror-handlinges6-promise

解决方案


//calling compareObjectMT ,Your return value is a Promise Object either resolve/reject

//s3, Key, getFileStat aruments value you are passing

compareObjectMT(s3, Key, getFileStat).then((value)=>{do something}) 
                                     .catch((err)=>console.error(err))

你在做什么类似于this..你在读取文件后的回调try catch..它不会从等待中捕获拒绝错误

你可以把所有 await 放在单个 try catch 块中

exports.s3Put = async (path) => {
try {
    fs.readFile(path, async (err, fileBinary) => {
        if (err) throw err;
        // console.log(data, 'data');
         try {
        const s3 = new AWS.S3();
        const Key = path.replace(process.env.WATCH_PATH, '');
        const getStat = await getFileStat(path);
        console.log(getStat, 'getstateeeeeeeeeeeeeeee');
        const compareObj = await compareObjectMT(s3, Key, getStat);
        console.log(compareObj, 'compareObj');
      }catch (e) {
    console.log(e, 'errorrrrrrrrrrrrr');
}
    });
} catch (e) {
    console.log(e, 'errorrrrrrrrrrrrr');
}

};

在此处输入图像描述


推荐阅读