我有以下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中添加oretry: ORInterface和剩余语句
发布于 2020-08-28 00:49:44
通过一些猜测(并假设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()返回的承诺(很有可能)将以任何顺序解决;这就是异步的本质。这可能对你的申请有影响,也可能无关紧要。
https://stackoverflow.com/questions/63624709
复制相似问题