2

I'm calling service api in loop and then I want to wait for the all results. I'm not sure how can I use Observable.forkJoin here.

Component:

for(let i=0;i<data.length;i++{
    this.component.getData(data[i].id).then((result: any) => {


                })
    }

Service:

getData(parameters:any): Promise<Object> {
    return this.query(parameters)
  }
2
  • Possible duplicate of Recursively calling an asynchronous API call Commented Dec 7, 2018 at 20:09
  • 1
    @Knostradamus I don't think there's anything recursive about this. Commented Dec 7, 2018 at 20:40

1 Answer 1

1

The key here is Promise.all, which waits for all promises to resolve before executing your callback.

let promises = data.map(d => this.component.getData(d.id));

Promise.all(promises).then(results => {
  console.log(results);
});
Sign up to request clarification or add additional context in comments.

2 Comments

We don't need for loop here? for(let i=0;i<data.length;i++{ let promises = data.map(d => this.component.getData(d.id));}
Ah, you must not be familiar with Array.map. It's functionally equivalent to your original for loop except that it also builds a new array from the values returned from the lambda function passed-into it. In this case, the lambda function passed to map returns a promise, so map returns an array of promises.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.