我有以下情况:
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()
的承诺.then()和.catch()。
我所想的是将它全部包装在一个巨大的新Promise中((解决,拒绝)=> {})但可能这是一种可怕的做法。
对此的输入表示赞赏。感谢。
答案 0 :(得分:0)
将它全部包装在一个巨大的新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 */
});