skip to Main Content

I want to make multiple parallel API calls using the same endpoint but different parameters. And subscribe to it if any of the request is complete. How can I handle this. This is my current approach. I am unsure of how to make parallel api calls and subscribe to it sequentially. Please suggest the better approach.

getProductDetails(id) {
  return this.http.get(
    `https://dummyjson.com/products/get_details?id=${id}`
  );
}

createProductDetails(productDetails)  {
}

ngOnInit() {
  const ids = ["a","b", "c", "d", "e", "f"];

  // api calls should happen in parallel manner
  from(ids).pipe(mergeMap((item) => {
    return this.getProductDetails(item)
  })).subscribe(response => {
    // it should create product details whenever response for any of the product is ready
    // this function should get called 6 times since their are 6 products
    this.createProductDetails(response)
  });
}

End goal is to make parallel api calls and start showing data as soon as the response is ready for any of the item

2

Answers


  1. I am not quite sure what the purpose of the pipe is in this situation. But I would suggest something like this using simple JavaScript promises.

    getProductDetails(id) {
      return this.http.get(
        `https://dummyjson.com/products/get_details?id=${id}`
      );
    }
    
    createProductDetails(productDetails)  {
    }
    
    ngOnInit() {
      const ids = ["a","b", "c", "d", "e", "f"];
    
      // get details for each id in parallel
      ids.forEach(id => {
        this.getProductDetails(id)
        .then(response => {
           // whenever a response is ready
           this.createProductDetails(response)
         })
      })
    }
    

    If you want to know when all promises have completed you can change forEach into map like so.

    // get details for each id in parallel
    const tasks = ids.map(id => {
      this.getProductDetails(id)
      .then(response => {
         // whenever a response is ready
         this.createProductDetails(response)
       })
    })
    
    // using .then()
    Promise.all(tasks)
    .then(() => console.log("tasks completed"))
    
    Login or Signup to reply.
  2. I think you are looking for CombineLatest
    In this you can calls multiple API’s simultaneously and get the response in one shot.

    combineLatest(
      API1,
      API2,
      API3
    )
      .subscribe(
        ([res1, res2, res3]) => {
      console.log(res1)
      console.log(res2)
      console.log(res3)
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search