gpt4 book ai didi

javascript - 只返回最里面的promise的catch并处理其他的

转载 作者:行者123 更新时间:2023-11-28 04:51:29 24 4
gpt4 key购买 nike

我有以下情况:

savePicture(newPicture, fileData){
return compressionUtil.makePictureAndThumbnail(newPicture).then((data) => {
let writeBig = fsUtil.writeFileToDisk(pictureFileName, data[0])
let writeSmall = fsUtil.writeFileToDisk(thumbnailFileName, data[1])

return Promise.all([writeBig, writeSmall]).then(() => {
let picToSave = {
uploaderUsername: fileData.username,
directory: fileDirectory,
fileName: fileName,
tags: fileData.tags,
description: fileData.description,
droneTaken: fileData.droneTaken,
isGenuine: isGenuine,
metadata: metadata
}
return Picture.create(picToSave)
})
})
}

我想做的是处理 compressionUtil.makePictureAndThumbnail()Promise.all([writeBig, writeSmall]) 可能被拒绝的情况,如下所示

savePicture(newPicture, fileData){
return compressionUtil.makePictureAndThumbnail(newPicture).then((data) => {
let writeBig = fsUtil.writeFileToDisk(pictureFileName, data[0])
let writeSmall = fsUtil.writeFileToDisk(thumbnailFileName, data[1])

return Promise.all([writeBig, writeSmall]).then(() => {
let picToSave = {
uploaderUsername: fileData.username,
directory: fileDirectory,
fileName: fileName,
tags: fileData.tags,
description: fileData.description,
droneTaken: fileData.droneTaken,
isGenuine: isGenuine,
metadata: metadata
}
return Picture.create(picToSave)
}).catch((err)=>{/*Handle promise.all error here*/})
}).catch((err)=>{/*Handle makePictureAndThumbnail error here*/})
}

但同时使 savePicture() 仅返回 Picture.create() 的 Promise .then() 和 .catch()。

我想到的是将所有内容包装在一个巨大的新 Promise((resolve,reject)=>{}) 中,但这可能是一种糟糕的做法。

对此的意见表示赞赏。谢谢。

最佳答案

wrapping it all in a giant new Promise((resolve,reject)=>{}) is probably a terrible practice.

是的indeed it is !

要仅处理来自 Promise 的拒绝,而不是来自 then 履行回调,您可以 use .then(…, …) instead of .then(…).catch(…) :

savePicture(newPicture, fileData){
return compressionUtil.makePictureAndThumbnail(newPicture).then((data) => {

return …
}, err => {
// ^ no `catch`
/* Handle makePictureAndThumbnail error here */
});
}

同样,

return Promise.all([writeBig, writeSmall]).then(() => {
let picToSave = { … }
return Picture.create(picToSave);
}).catch(err => {
/* Handle all errors from writeBig, writeSmall and create */
});

return Promise.all([writeBig, writeSmall]).then(() => {
let picToSave = { … }
return Picture.create(picToSave).catch(err => {
/* Handle errors from create */
});
}, err => {
/* Handle all errors from writeBig and writeSmall */
});

关于javascript - 只返回最里面的promise的catch并处理其他的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42877252/

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