Patrioticcow Patrioticcow - 4 months ago 37
Javascript Question

Promises in Ionic 2 / Angular 2, how to?

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

Answer

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;
    });
}
Comments