【发布时间】:2019-02-24 20:47:24
【问题描述】:
我正在开发一个受此答案启发的承诺链: https://stackoverflow.com/a/44955506/7485805
我想打破这个 for 循环,以便正确处理链的拒绝。我只是想我不能在链的.catch 方法中使用break。
如果有帮助,这是我的代码:
function pro (arr) {
let chain = Promise.resolve();
const self = {req: {}, res: {}};
const length = arr.length;
return new Promise((resolve, reject) => {
for(let i=0; i<length; i++){
chain = chain
.then(() => arr[i].call(self) )
.then(() => {
if(i === (length - 1) )
resolve();
})
.catch(e => {
reject(e);
})
}
})
.then(() => {
return self
})
.catch(e => {
throw new Error (e);
})
}
const x = function () {
const self = this;
return new Promise(resolve => {
self.req = {key: "value"}
resolve();
})
}
const y = function () {
const self = this;
return new Promise((resolve, reject) => {
console.log(self);
reject();
})
}
const z = function () {
const self = this;
return new Promise((resolve, reject) => {
console.log('failed');
})
}
pro([x, y, z])
.then((self) => {
console.log('final',self);
})
.catch(e => {
console.log('error', e);
})
x, y, z 是函数pro 中链接在一起的三个函数
而x 解析成功,y 被执行但被拒绝。
我想停止 z 的执行,因为继续执行毫无意义,并且可能会在实际代码中产生错误。
另外,如果有人可以为这段代码推荐一个更好的版本:
.then(() => {
if(i === (length - 1) )
resolve();
})
注意:我不能使用await,因为此代码将在服务器端执行,使用await 可能会阻止其他传入请求。
【问题讨论】:
-
“我想打破这个 for 循环” 请参阅answerRun multiple recursive Promises and break when requested。为什么需要打破循环来处理错误? "break" 在上下文中是什么意思?
-
@Bergi 请查看链接:es6console.com/jsjdb5rx
-
"y 被执行但被拒绝,我想停止执行 z" - 呃,如果你以与答案相同的方式构建你的链你链接了,那么
z根本不会被执行?!您的问题是.catch(e => { reject(e); })实际上并没有处理错误 -
this 是您想要实现的目标吗?
标签: javascript for-loop es6-promise