如何等待forkJoin执行完成后再执行后续业务逻辑
问题:如何等待forkJoin执行完成后再运行后续业务逻辑
本文是某帖子的续篇,因与原问题不同故新开帖子提问。
代码示例
export interface indexLogic { [id: number]: Detail; } async ngOnChanges(){ await getData(); // 如何确保下面的方法只在this.indexLogic被填充后执行 await useInformationReceivedFromgetData(); } async getData(){ getInformations().subscribe( informations => { let subs = []; for (const information of informations) { subs.push(getOtherDetails(information.id).pipe( map(data => ({ id: information.id, data })) // <--- )); } this.indexLogic = []; forkJoin(subs).subscribe(objects => { objects.forEach(({id, data}) => { this.indexLogic.push({[id]:data}) }); }); } ); }
解决方案
核心问题是getData作为异步函数,内部使用subscribe却未返回Promise,导致await getData()无法等待异步操作完成。只需将RxJS Observable转换为Promise,让await能正确等待流程结束。
修改后代码
export interface indexLogic { [id: number]: Detail; } async ngOnChanges(){ await getData(); // 此时this.indexLogic已完成填充 await useInformationReceivedFromgetData(); } async getData(): Promise<void> { // 将Observable转为Promise,确保只取第一个响应值 const informations = await getInformations().pipe(first()).toPromise(); // 生成请求数组 const subs = informations.map(information => getOtherDetails(information.id).pipe( map(data => ({ id: information.id, data })) ) ); this.indexLogic = []; // 等待forkJoin所有请求完成 const objects = await forkJoin(subs).pipe(first()).toPromise(); objects.forEach(({id, data}) => { this.indexLogic.push({[id]: data}); }); }
关键说明
- 若使用RxJS 7及以上版本,推荐用
firstValueFrom替代已废弃的toPromise(),示例:import { firstValueFrom } from 'rxjs'; // ... const informations = await firstValueFrom(getInformations().pipe(first())); const objects = await firstValueFrom(forkJoin(subs)); - 移除嵌套
subscribe,改用await链式处理,既保证执行顺序,也让逻辑更清晰。
内容的提问来源于stack exchange,提问作者Vivek Shukla
相关产品推荐
相关产品推荐

