javascript - 在 for 循环中打破 Promise 链
问题描述
我正在研究受此答案启发的承诺链: https ://stackoverflow.com/a/44955506/7485805
我想打破这个 for 循环,以便正确处理链的拒绝。我只是想我不能在链break
的方法中使用。.catch
如果有帮助,这是我的代码:
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
是在函数While中链接在一起的三个函数,x
成功解析,y
执行但被拒绝。
我想停止执行,z
因为继续没有意义,并且可能在实际代码中产生错误。
另外,如果有人可以为这段代码推荐一个更好的版本:
.then(() => {
if(i === (length - 1) )
resolve();
})
注意:我不能使用await
,因为此代码将在服务器端执行,并且使用await
可能会阻止其他传入请求。
解决方案
async/await
使用语法要容易得多:
async function pro(arr) {
const self = {req: {}, res: {}};
for(const f of arr) await f.call(self);
return self;
}
async function pro(arr) {
const self = {req: {}, res: {}};
for(const f of arr) await f.call(self);
return self;
}
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("y failed");
})
}
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);
});
推荐阅读
- angular - 如果 Angular 的本地存储中有数据,如何将默认主页路径“”更改为不同的路由
- javascript - 在 Playwright 中使用关键字数组并循环遍历脚本
- spring - spring-boot中如何实现行级授权?
- excel - Excel VBA:如何让 COUNTIF 函数不将文本单元格“1.1”和“1.10”作为重复项?
- configuration - Hue 和 Impala 连接问题 Thrift Handle 异常
- python - Pymongo 和更新记录
- node.js - 未找到模块:错误:无法解析 'D:\laravel projects\codeGram\resources\js\components' 中的 '../../../vue-temp/vue-editor-bridge'
- r - 如何获得这些由“;”分隔的字符串的唯一出现?
- python-3.x - 如何在 Docker PUSH 中排除 VENV
- amazon-web-services - 在 AWS SWF 工作流程中安排的计时器是否会无法返回时钟?