【发布时间】:2019-05-17 19:53:45
【问题描述】:
我有一个承诺链,其中某些事情发生在 resolve 和不同的事情发生在拒绝,但有时我想跳过所有以下 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)});
在第一个 then 如果代码进入拒绝案例,我想跳过所有剩余的 then。然而它并没有,因此所有随后的事情都会发生并且都失败了。唯一应该继续的拒绝是在第三次我确实想要返回承诺时。
【问题讨论】:
-
.catch只是一个美化的.then。它在内部调用它。 -
除非需要,否则不要将原始 promise 与 async/await 混合使用。它只会让一切变得复杂。
-
您能否详细说明您的意思,请 estus。我这样做的原因是因为dropbox api上有节流,所以我需要一件一件做
-
@ArthurLeCalvez 你应该只使用
for (const audit in req) { … await … }循环。 rarely 需要使用then,而您只能使用await。
标签: javascript node.js promise chain