等待地图功能完成打字稿

时间:2020-07-01 09:02:27

标签: typescript dictionary

for每个循环不会等待map函数完成,因此id是不确定的。 我如何确保所有ID都已映射?

getIndexes(){
 this.http.get<{data: {id: number, caption:string}[], paging: any, next: string}>(this.baseUrl +'me/media/?access_token=' + this.users + '&fields=id,caption&limit=9',
{responseType:"json"}).subscribe(response =>
  {
    const data = response.data.map(async l => {
      l.id
    })
    data.forEach(
    id => {
      this.http.get<{ media_url: string; id: string; }>(this.baseUrl + id + '/?access_token=' + this.users + '&fields=media_url').subscribe(res => {
        console.log(this.list);
        this.list.push(res.media_url);
        console.log(this.list);
        this.gallery.next(this.list);
      });
    }

  );
  }
)
}

1 个答案:

答案 0 :(得分:1)

尝试使用这样的等待方式

getIndexes(){
 this.http.get<{data: {id: number, caption:string}[], paging: any, next: string}>(this.baseUrl +'me/media/?access_token=' + this.users + '&fields=id,caption&limit=9',
{responseType:"json"}).subscribe(async response =>
  {
    const data =await response.data.map(l => {
      l.id
    })
    data.forEach(
    id => {
      this.http.get<{ media_url: string; id: string; }>(this.baseUrl + id + '/?access_token=' + this.users + '&fields=media_url').subscribe(res => {
        console.log(this.list);
        this.list.push(res.media_url);
        console.log(this.list);
        this.gallery.next(this.list);
      });
    }

  );
  }
)
}