如何解决如何在Angular9中将Subsink api调用转换为Promise.all?
我有以下async
函数,它使用Subsink
import {SubSink} from 'subsink';
...
...
async retryClick() {
for (let i = 0; i < this.Id.length; i++) {
const res = await this.serviceC.status(this.hostName[i]);
const qId = res.rows[0].qid;
const oretry: ORInterface = {
oQId: qId,reason: this.reason
};
this.subs.sink = this.serviceB.retry(oretry)
.subscribe(s => {
if (i === this.serverId.length - 1) {
this.dialog.close();
}
});
}
}
我想使用Promise.all
Promise.all(this.hostName.slice(0,this.Id.length).map(hostName =>
this.serviceC.status(hostName)
.then(res => console.log(res.rows[0].qid))
)).then(() => this.dialog.close());
使用Promise.all
的上述代码可以正常工作
这里的Id
类型为any
如何在以上oretry: ORInterface
中添加Promise.all
和其余语句?
解决方法
经过一些猜测(并假设this.hostName.slice(0,this.Id.length).map(...)
是正确的),看来您正在尝试执行此操作...
Promise.all(this.hostName.slice(0,this.Id.length).map((hostName) => {
return this.serviceC.status(hostName)
.then(res => {
// Here `this.serviceB.retry(oretry).subscribe` must be promisified,// in order to keep the promise chain,thence `Promise.all()` informed.
return new Promise((resolve,reject) => {
const oretry: ORInterface = {
'oQId': res.rows[0].qid,'reason': this.reason
};
this.serviceB.retry(oretry).subscribe(resolve); // No need to test if (i === this.serverId.length - 1).
// The last .subscribe(resolve) to fire will trigger this.dialog.close() below
});
});
}))
.then(() => {
this.dialog.close();
})
.catch(err => {
console.log(err);
this.dialog.close(); // presumably
});
...但请注意,最后触发的.subscribe(resolve)
不一定与最终的this.serviceC.status(hostName)
调用相对应。 .map()
返回的承诺将(以一切可能性)以任何顺序解决;这就是异步的本质。这可能对您的应用程序无关紧要。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。