简体   繁体   中英

Wait for map function to finish typescript

The for each loop does'nt wait for the map function to finish so the id is undefined. How can i make sure all the id's are mapped?

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);
      });
    }

  );
  }
)
}

Try using await like this

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);
      });
    }

  );
  }
)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM