[英]How can i break my promise chain in certain reject cases
我有一連串的承諾,其中某些事情發生在解決上,而其他事情發生在拒絕上,但是有時我想跳過以下所有then
語句。
我的代碼看起來像這樣
await req.reduce((promise, audit) => {
let globalData;
return promise.then(_ => this.add(audit)
.then((data)=> {
globalData = data; console.log('1');
return dropbox_functions.createFolder(data.ui, data)
},
(error)=> {
failed.push({audit: audit, error: 'There was an error adding this case to the database'});
console.log('1.1'); i = i + 1; socket.emit('bulkAddUpdate', i/arrLen);
throw new Error('There was an error adding this case to the database');
})
.then((data)=>{
console.log('2');
return dropbox_functions.checkScannerFolderExists(audit.scanner_ui)
},
(error)=>{
console.log('2.1');issues.push({audit: globalData, error: 'There was an error creating the case folder in dropbox'});
i = i + 1;socket.emit('bulkAddUpdate', i/arrLen);
throw new Error('There was an error creating the case folder in dropbox');
})
.then((data)=>{
console.log('3');
return dropbox_functions.moveFolder(audit.scanner_ui, globalData.ui)},
(error)=>{
console.log('3.1');issues.push({audit: globalData, error: 'No data folder was found so an empty one was created'});
return dropbox_functions.createDataFolder(globalData.ui)
})
.then(()=> {
console.log('4');
success.push({audit:globalData});
i = i + 1;socket.emit('bulkAddUpdate', i/arrLen);},
(error)=> {
issues.push({audit: globalData, error: 'Scanner folder found but items not moved'});console.log('4.1');
})
.catch(function(error){
console.log(error)
})
);
}, Promise.resolve()).catch(error => {console.log(error)});
在第一個代碼中,如果代碼進入拒絕的情況,我想跳過所有其余的代碼。 但是,它沒有發生,因此所有后續操作都將發生並且都將失敗。 唯一應該繼續前進的拒絕是在第3次時,當我確實要返回承諾時。
通常,您的問題是某些錯誤是致命的,而有些則不是。 您希望致命錯誤一路跌到谷底,但非致命錯誤要按順序處理。
將所有“致命”錯誤保持在最高級別,並將非致命錯誤嵌套在then塊內。 我還建議不要使用“ then(fn,fn)”格式-始終明確指定捕獲量。
例:
return fnA().then(dataA => {
return fnB(dataA).catch(error => {
console.log("fnB got a non-fatal error, I'm fixing it.");
return fnFixB();
});
})
.then(dataB => fnC())
.then(dataC => {
return fnD(dataC).catch(error => {
console.log("fnD didn't work, I'm fixing it.");
return fnFixD();
});
}).catch(error => {
console.log("Sorry: one of fnA, fnFixB, fnC, or fnFixD must have broken.");
});
在此示例中,如果fnA
或fnC
拒絕,那么您將fnC
谷底。 但是, fnB
和fnD
產生可從中恢復的錯誤(盡管如果修復fnFixB
和fnFixD
失敗,您也將fnFixD
谷底)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.