Search code examples
node.jsforeachobservablewait

Waiting for observable inside a foreach


I have this code:

users() {
    ...
    cookies.forEach(user=> {
        this.save(user);
    });
}

save(user) {
    this.userName = user.split(';')[0];
      this.userService.saveUser(this.userName).subscribe(() => {
          ...
        });
    });
  }

The thing is that it goes over the forEach with the first user and its userName. Then, it should execute saveUser, but before executing it, it iterates over the forEach again. So the user has changed and its username too. So, at the end, I always save the same user.

Is there a way to make that the forEach waits for the saveUser?

Thank you so much!


Solution

  • I assume that subscribe function uses a promise. As you said when iterating over an Array and executing a promise on each iteration, the iterator does not wait to the promise to be resolved.

    You can aggregate all your promises in the forEach like this:

    users() {
    ...
        let promises = []
        cookies.forEach(user=> {
            promises.push(this.save(user));
        });
        Promise.all(promises).then(results => {.......});
    }