0

How to solve the asynchronous issue when calling the service inside the for loop

  let historyMo =[];
    for (let i = 0; i < history.length; i++) {
             return  this.userService.getNodes(history[i]).subscribe((result: any) => {

                  historyMo.push(result);
              });

           }  

Some times it returns empty array value when doing console.log(historyMo)

1 Answer 1

1

Avoid subscribing to multiple observables in a loop. It will lead to multiple simultaneous subscriptions and potential memory leaks.

Try to instead use RxJS forkJoin or combineLatest functions.

let historyMo =[];
let requests = [];
for (let i = 0; i < history.length; i++) {
  requests.push(this.userService.getNodes(history[i]);
}

forkJoin(requests).subscribe(
  response => {
    this.historyMo = response;
    console.log(this.historyMo);
  }
);

forkJoin() emits only when all the observables complete - makes it ideal for HTTP observables.

combineLatest() is used to subscribe to observables that are persistent data streams.

Besides, any statements that directly depend on the historyMo variable should be inside the subscription. It's an asynchronous variable and it cannot be accessed synchronously.

Sign up to request clarification or add additional context in comments.

Comments

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.