2

I have two functions:

this.geQuizStorage();
this.getQuizData();

geQuizStorage() {
    this.quizStorage.getAnswers().then(data => {
        return data;
    });
}

getQuizData() {
    this.quizData.getQuiz().then(data => {
        return data;
    });
}

I am trying use promises for the 2 functions and wait until both are done, something like:

http.when(this.geQuizStorage(), this.getQuizData()).when(data => {
    // data[0] first function response
    // data[1]
})

any ideas how to do this in Ionic 2 / Angular 2

Patrioticcow
  • 26,422
  • 75
  • 217
  • 337

2 Answers2

5

You can do this with ES6 promise's all function. No need for external libraries.

Promise.all([this.geQuizStorage(), this.getQuizData()]).then(data => {
  //do stuff with data[0], data[1]
});

Your functions should return promises in order for this to work, so I suggest the following modification:

geQuizStorage() {
    return this.quizStorage.getAnswers().then(data => {
        return data;
    });
}

getQuizData() {
    return this.quizData.getQuiz().then(data => {
        return data;
    });
}
Yaron Schwimmer
  • 5,327
  • 5
  • 36
  • 59
  • Don't I need to resolve some promise and return it inside my 2 functions? – Patrioticcow Jul 27 '16 at 14:38
  • I missed the part where your functions don't return promises... but all you need is to make `getQuizStorage` and `getQuizData` return promises. This can be easily accomplished by adding `return` before calling the service function. See edited answer. – Yaron Schwimmer Jul 27 '16 at 15:44
  • Can you make them return data? – Menachem Hornbacher Mar 19 '17 at 00:42
  • i'm doing this, but i have an issue that if the request fails, promise.all enter the rejection function but with an error : Uncaught (in promise) i'm opening the issue here can you help me : https://stackoverflow.com/questions/44460438/promise-all-not-access-in-rejection-function?noredirect=1#comment75922854_44460438 – Joe Sleiman Jun 12 '17 at 06:31
3

Basically you don't need to create another wrapper function for your service call, just to return a data(unless you have your validation logic out there to validate data). Then pass those two function in Observable.forkJoin by passing method promises/observable's & subscribe over that observable to wait till those get complete.

 Observable.forkJoin([this.getQuizData(),this.geQuizStorage()])
  .subscribe(data => {
     console.log(data[0], data[1]);
     //both call succeeded
});
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299