[英]How to make an async call inside other async call with a foreach loop
我真的很想改进并了解如何更好地做到这一点。 这段代码正在运行,但我相信这里有问题。 想法如下:
1:我对 API 进行第一次 HTTP 调用并获取数据。
2:我使用的数据是 matchHistoryArr ,它有一个包含 10 个“gameIds”的数组,我需要将它们通过 forEach(loop) 传递给 this.summ.getMatches(gameId) 并将它们推送到需要与比较的新本地数组另一个数组对其进行排序(因为 async 不会对其进行排序),因此在搜索了很多之后,我可以像这样解决它。 (我会在代码中标记)注意:这是我遇到大问题的地方,
3:现在我需要从其他端点获取更多数据,但我相信在继续之前我必须更好地订购代码。
组件.ts
onSubmit(){
** 1 **
this.summ.getSummoner(this.summoner.name,this.summoner.regionId)
.subscribe( (data:any) => {
let matchHistoryArr = data.matchHistory
let gameIdArray = matchHistoryArr.map( element => element.gameId)
const subscribers: Subscriber<any>[] = [];
const promiseMatchesArray = [];
** 2 **
matchHistoryArr.forEach( element => {
promiseMatchesArray.push( this.summ.getMatches(element.gameId).toPromise().then( match => {
subscribers.push(match)
}));
});
Promise.all(promiseMatchesArray).then( a =>{
if ( subscribers.length === matchHistoryArr.length ){
let arraySort = [];
arraySort = subscribers
let dataParticipants
let matchesArraySorted = arraySort.sort((a, b) => {
return gameIdArray.indexOf(a.gameId) - gameIdArray.indexOf(b.gameId);
});
this.matchesArray = matchesArraySorted
matchesArraySorted.forEach( x => {
dataParticipants = x.participants
});
if ( dataParticipants.length === 10 ){
this.dataParticipants = dataParticipants
}
}
});
this.matchHistory = matchHistoryArr
this.SummInfo = data.summonerdata;
});
}
服务.ts
export class SummonerService {
constructor( private http:HttpClient ) { }
summonerName
getSummoner(summonerName,regionId){
this.summonerName = summonerName
return this.http.get(`http://localhost:3000/summName/${summonerName}/${regionId}` )
.pipe(
map( (data:any) => data)
)};
getChampImage(champId){
return this.http.get(`https://raw.communitydragon.org/latest/plugins/rcp-be-lol-game-data/global/default/v1/champion-icons/${champId}.png`)
};
getMatches(gameId){
return this.http.get( `http://localhost:3000/match/${gameId}` )
.pipe(
map( (data:any) => this.uploadData(data))
)};
本质上,您的示例可以归结为两个步骤:
我建议一直坚持使用 observables,除非有令人信服的理由使用 Promise。
concatMap
切换到新的 observableforkJoin
并行运行onSubmit() {
this.summ.getSummoner(this.summoner.name, this.summoner.regionId)
.pipe(
tap((summoner) => this.matchHistory = summoner.matchHistory),
concatMap((summoner: any) => {
const observables = this.matchHistory
.map(element => this.summ.getMatches(element.gameId));
return forkJoin(observables)
}),
map(matchesArray => {
// TODO: perform sorting
return matchesArray;
})
).subscribe(matchesArray => {
});
}
我省略了您的排序以保持答案简单。
matchesArray
是反映输入observables
的结果数组。
您想要执行的任何排序都可以在map
运算符中执行。
您想从管道中保存的任何状态都可以在tap
操作器中完成。
组合 observable 的关键是要记住只有一个顶级订阅者。 Observables 可以以任何你能想到的使用管道操作符的方式组合。 这就是为什么我建议坚持使用 observables。 在复杂的场景中,它们比承诺更强大。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.