简体   繁体   English

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

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

I making two api call using Promise.all and toPromise() as below:我使用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);
    });

Here this.serviceB.retry(oretry) is being executed correctly.这里this.serviceB.retry(oretry)被正确执行。 But, this.serviceB.createDbEntry(sentry) is being executed twice.但是, this.serviceB.createDbEntry(sentry)被执行了两次。

The hostName array has two values: hostA and hostB hostName array有两个值: hostAhostB

Similarly, the Id array has two values: Id1 and Id2同样, Id array有两个值: Id1Id2

Now, the issue is that this.serviceB.createDbEntry(sentry) is creating four db entries as below:现在,问题是this.serviceB.createDbEntry(sentry)正在创建四个数据库条目,如下所示:

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

It should only make two entries:它应该只输入两个条目:

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

As your hostname and id seem related, you should not do a map over the whole this.id slice, but just take the one that corresponds to the current hostname.由于您的主机名和 id 似乎相关,因此您不应该对整个this.id切片进行map ,而只需取与当前主机名对应的那个。

So, get the sequential index of the current hostname as follows:因此,获取当前主机名的顺序索引如下:

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

And then further down, don't do another, nested Promise.all , but:然后再往下,不要再做另一个嵌套的Promise.all ,但是:

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

Also, fix the spelling of sretry in that last line (you have sentry )另外,修复最后一行中sretry的拼写(您有sentry

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

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