javascript - 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');
}
};
解决方案
//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');
}
};
推荐阅读
- javascript - Mobx 计算不工作
- sql - 模拟一个 sql 可重现的例子
- c++ - 为什么 fetch_sub 不是释放操作?
- tensorflow - 来自 tf.train.import_meta_graph 的 UnicodeDecodeError
- r - 在 R 中,为什么 all(numeric(0)) 给出 TRUE 而 any(numeric(0)) 给出 FALSE?
- npm - 如何让 Modernizr 与 Webpack 4 一起工作
- c# - 参数在非常简单的数组上超出范围
- python - Python pandas获取数据框中组的第一个和最后一个索引,如果第一个也是最后一个则重复
- python - 使用感叹号对凯撒密码函数进行加密
- asp-classic - 在 Server.CreateObject("Scripting.FileSystemObject") 中创建要在 GetFolder 中使用的虚拟目录 IIS7