繁体   English   中英

承诺全部进行四个 api 调用而不是两个 api 调用

[英]Promise all making four api calls instead of two api calls

我使用Promise.alltoPromise()进行了两个 api 调用,如下所示:

Promise.all(this.hostName.slice(0, this.Id.length).map((hostName) => {
    return this.serviceC.status(hostName)
        .then(res => {
            const oretry: ORInterface = {
                oQid: res.rows[0].qid,
                reason: this.reason
            };
            return this.serviceB.retry(oretry).toPromise();
        })
        .then(() => {
            return Promise.all(this.Id.slice(0, this.Id.length).map(id => {
                const sretry: SDInterface = {
                    hostName,
                    Id: id,
                    reason: this.reason
                };

                this.serviceB.createDbEntry(sentry).toPromise();
                }));
            });
    }))
    .then(() => {
        this.dialog.close();
    })
    .catch(err => {
        console.log(err);
    });

这里this.serviceB.retry(oretry)被正确执行。 但是, this.serviceB.createDbEntry(sentry)被执行了两次。

hostName array有两个值: hostAhostB

同样, Id array有两个值: Id1Id2

现在,问题是this.serviceB.createDbEntry(sentry)正在创建四个数据库条目,如下所示:

`hostA` `Id1`
`hostA` `Id2`
`hostB` `Id1`
`hostB` `Id2`

它应该只输入两个条目:

`hostA` `Id1`
`hostB` `Id2`

由于您的主机名和 id 似乎相关,因此您不应该对整个this.id切片进行map ,而只需取与当前主机名对应的那个。

因此,获取当前主机名的顺序索引如下:

Promise.all(this.hostName.slice(0, this.Id.length).map((hostName, i) => {
//                                                              ^^^^

然后再往下,不要再做另一个嵌套的Promise.all ,但是:

.then(() => {
    let id = this.Id[i];
    const sretry: SDInterface = {
        hostName,
        Id: id,
        reason: this.reason
    };
    return this.serviceB.createDbEntry(sretry).toPromise();
});

另外,修复最后一行中sretry的拼写(您有sentry

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM