[英]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
和toPromise()
进行了两个 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
有两个值: hostA
和hostB
Similarly, the Id array
has two values: Id1
and Id2
同样,
Id array
有两个值: Id1
和Id2
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.