getEnrolledPlayers应该从数据库中获取“玩家”对象的数组,然后将其传递给matchMaking函数。但是,它不能正确传递。
我尝试添加可观察的事物,在订阅中玩耍
initializeEvent(eventId: string) {
const enrolledPlayers: PlayerStat[] = [];
this.getEnrolledPlayers(eventId)
.subscribe((playerIds: string[]) => {
for (const playerId of playerIds) {
this.dataService.fetchSinglePlayer(playerId)
.subscribe((playerStat: PlayerStat) => enrolledPlayers.push(playerStat));
}
this.matchMaking(enrolledPlayers);
});
}
当我调用这些系列的异步函数时,enrolledPlayers []的计算正确(包含7个元素的数组),但是没有正确地调用matchMaking()函数。我认为这是因为异步运行时。
答案 0 :(得分:3)
是的。绝对是由于内部const query = `SELECT * FROM document_metadata m
LEFT OUTER JOIN document_attributes a
ON a.document_id = m.id;`
db.query(query)
解析值的时间差而引起的问题。
我建议使用forkJoin
并等待所有值解析后再调用subscription
。
尝试一下:
matchMaking
或带有一个initializeEvent(eventId: string) {
const enrolledPlayers: PlayerStat[] = [];
this.getEnrolledPlayers(eventId)
.subscribe((playerIds: string[]) => {
const playerInfos$ = playerIds.map(playerId => this.dataService.fetchSinglePlayer(playerId));
forkJoin(...playerInfos$)
.subscribe(enrolledPlayers: PlayerStat[] => this.matchMaking(enrolledPlayers));
});
}
subscribe
答案 1 :(得分:0)
this.matchingMaking(enrolledPlayers)
由于异步而在enrolledPlayers准备就绪之前执行。
您需要将this.matchingMaking(enrolledPlayers)
放入内部subscribe()
中,然后进行for循环。
this.getEnrolledPlayers(eventId)
.subscribe((playerIds: string[]) => {
for (const playerId of playerIds) {
this.dataService.fetchSinglePlayer(playerId).subscribe((playerStat: PlayerStat) => {
enrolledPlayers.push(playerStat);
});
}
this.matchMaking(enrolledPlayers);
});