meallhour
meallhour

Reputation: 15581

Promise all making four api calls instead of two api calls

I making two api call using Promise.all and toPromise() as below:

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. But, this.serviceB.createDbEntry(sentry) is being executed twice.

The hostName array has two values: hostA and hostB

Similarly, the Id array has two values: Id1 and Id2

Now, the issue is that this.serviceB.createDbEntry(sentry) is creating four db entries as below:

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

It should only make two entries:

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

Upvotes: 1

Views: 48

Answers (1)

trincot
trincot

Reputation: 350310

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.

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:

.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)

Upvotes: 1

Related Questions