How do list.map wait request response?

I have a map with request inside, but I detected the map don't wait the request response to get next index.

this.products = [];
productList.map((product) => {
this.productService.getProductInfo(product).subscribe(productData => {
   productData.selected = true;
   this.products.push(productData);
  });
});

there's a way do the map wait the request response?

1 answer

  • answered 2018-12-05 20:46 William Lohan

    Fist I'd make an array of requests:

    const productRequests: Observable<Product>[] = productList.map(productId => this.productService.getProductInfo(productId));
    

    then next you combine the observables, you do multiple ways, I assume perservering the order is important

    // loads all at once, preserves order
    forkJoin(...productRequests).subscribe(productData => {
      this.products = productData;
    });
    

    or

    // loads one by one, sort post result to preserve order
    this.products = [];
    merge(...productRequests).subscribe(productData => {
      this.products.push(productData);
      this.products.sort((a, b) => {
        if (a.id < b.id) {
          return -1
        }
        if (a.id > b.id) {
          return 1
        }
        return 0;
      });
    });
    

    https://stackblitz.com/edit/angular-map-request