gpt4 book ai didi

javascript - 如何处理 Node.JS 中的 UnhandledPromiseRejectionWarning

转载 作者:行者123 更新时间:2023-12-01 00:07:05 25 4
gpt4 key购买 nike

我有一些使用 request 模块从 URL 获取图像并将其作为 Promise 返回的方法,它可以工作,但是当找不到图像时,它会使用状态代码拒绝 Promise 404.我研究了这个警告,据说要处理拒绝,你必须在 then() 之后设置一个 catch 回调,但我不使用 then(),我使用 async/await。

这是获取图片的代码:

/**
* Returns picture from S3
* @param {String} filename Name of the file with extension
* @returns {String} Base64 string of the file
*/
getPictureFromS3: function (filename) {
return new Promise((resolve, reject) => {
let url = this.getURLFromS3(filename);
request(url, (err, res, body) => {
if (err) reject(err);
if (res.statusCode !== 200) {
reject(`Invalid status code <${res.statusCode}>`);
}
resolve(new Buffer.from(body).toString('base64'));
});
});
}

这就是我调用该方法的方式:

try{
socket.on('server get pictures', () => db.getPictures(data=>{
if(data!==null){
data.forEach(async e=>{
let picture = await utils.getPictureFromS3(e.getFilename());
});
}
}));
}catch(err){
console.log(err);
}

完整警告:

(node:256) UnhandledPromiseRejectionWarning: Invalid status code <404>
(node:256) 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: 1)
(node:256) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

使用 Node v10.14.2。

最佳答案

这里有两个问题

  • 您关心尝试在 forEach 内执行异步操作,这不适用于 Promise。如果您可以并行执行操作,则需要使用 for..of 循环或 Promise.all

  • 异常是在监听器内部引发的,因此它不会在外部冒泡,因此您的 catch 不会被执行。你需要将你的 try catch 移到里面。类似这样

socket.on("server get pictures", () =>
db.getPictures(data => {
if (data !== null) {
for(const e of data) {
try {
let picture = await utils.getPictureFromS3(e.getFilename());
} catch (err) {
console.log(err);
}
}
}
})
);

关于javascript - 如何处理 Node.JS 中的 UnhandledPromiseRejectionWarning,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60307625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com