首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Promise.all中将子接收器api调用转换为Angular9?

如何在Promise.all中将子接收器api调用转换为Angular9?
EN

Stack Overflow用户
提问于 2020-08-27 22:02:07
回答 1查看 65关注 0票数 0

我有以下async函数,它使用Subsink

代码语言:javascript
复制
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编写上面的代码

代码语言:javascript
复制
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很好地工作。

在这里,Idany类型

如何在上面的oretry: ORInterface中添加oretry: ORInterface和剩余语句

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-28 00:49:44

通过一些猜测(并假设this.hostName.slice(0, this.Id.length).map(...)是正确的),您似乎正在尝试这样做……

代码语言:javascript
复制
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()返回的承诺(很有可能)将以任何顺序解决;这就是异步的本质。这可能对你的申请有影响,也可能无关紧要。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63624709

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档