esseara
esseara

Reputation: 880

Angular 4 - Promise.all not working

I'm using Promise.all(...) to wait for some REST calls to end before using the data I need from the server. The code structure is the following:

const promise1 = this.myService.myFirstRestFunction(a.id).toPromise().then(s => variable1 = s;);

const promise2 = this.myService.mySecondRestFunction(b.id).then(r => {
  this.myService.myThirdRestFunciont(r.id).then(c => variable2 = c);
});

Promise.all([promise1, promise2]).then(p => {
  this.myService.getData(variable1.id, variable2.id)
    .subscribe(...);
});

But variable2 is undefined when I try to get the id field. Is this related to the myThirdRestFunction() that is called inside? If this is the case, how can I manage such subsequential REST calls and wait for the most internal data to be fetched? Thanks.

EDIT: I changed my code following @Suren Srapyan and @Sachila Ranawaka answers.

const promise1 = this.myService.myFirstRestFunction(a.id).toPromise();

const promise2 = this.myService.mySecondRestFunction(b.id).then(r => {
  this.myService.myThirdRestFunciont(r.id);
});

Promise.all([promise1, promise2]).then(p => {
  this.myService.getData(p[0].id, p[1].id)
    .subscribe(...);
});

In this case I get correctly p[0] but p[1] is still undefined. If I try to resolve the second promise, for example:

const promise2 = this.myService.mySecondRestFunction(b.id).then(r => {
      this.myService.myThirdRestFunciont(r.id).then(c => console.log(c));
    });

The object c is correctly logged, so p[1] should not be undefined.

Upvotes: 1

Views: 935

Answers (2)

Suren Srapyan
Suren Srapyan

Reputation: 68655

You don't need to assign to the variables. Promise.all will resolve all promises if it could and pass their results into the p parameter as array.

Just return your data from the then functions and access via p[0] and p[1] in the Promise.all(...).then(p => ...)

const promise1 = this.myService.myFirstRestFunction(a.id).toPromise()

const promise2 = this.myService.mySecondRestFunction(b.id)
                               .then(r => this.myService.myThirdRestFuncion(r.id));

Promise.all([promise1, promise2]).then(p => {
  this.myService.getData(p[0].id, p[1].id).subscribe(...);
});

I don't know what your promises return, so I provide p[0].id. Change this according to your result.

For more beautiful code you can also destruct parameters

Promise.all([promise1, promise2]).then(([var1, var2]) => {
    this.myService.getData(var1.id, var2.id).subscribe(...);
});

Upvotes: 1

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41397

Don't resolve the first 2 promises. Promise.all will resolve all the promises for you

const promise1 = this.myService.myFirstRestFunction(a.id).toPromise() 
const promise2 = this.myService.mySecondRestFunction(b.id) 

Promise.all([promise1, promise2]).then(p => {
  this.myService.getData(variable1.id, variable2.id)
    .subscribe(...);
});

Upvotes: 0

Related Questions