我有一些方法使用该request
模块从URL获取图像并将其作为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.
使用节点v10.14.2。
这里有两个问题
您很想尝试在内部执行异步操作forEach
,但该操作不能与Promise一起使用。您需要使用for..of
循环,或者Promise.all
可以并行执行操作。
例外是在侦听器内部引发,因此它不会在外部冒泡,因此您的捕获将不会执行。您需要将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);
}
}
}
})
);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句