问题描述
我使用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);
});
此处this.serviceB.retry(oretry)
的执行正确。
但是,this.serviceB.createDbEntry(sentry)
被执行两次。
hostName array
有两个值:hostA
和hostB
类似地,Id array
有两个值:Id1
和Id2
现在,问题在于this.serviceB.createDbEntry(sentry)
正在创建四个数据库条目,如下所示:
`hostA` `Id1`
`hostA` `Id2`
`hostB` `Id1`
`hostB` `Id2`
它只能输入两个条目:
`hostA` `Id1`
`hostB` `Id2`
解决方法
由于您的主机名和ID似乎相关,因此您不应在整个map
片上执行this.id
,而应采用与当前主机名相对应的那个。
因此,获取当前主机名的顺序索引,如下所示:
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
的拼写