javascript - Promises in Ionic 2Angular 2, how to? - Stack Overflow

I have two functions:this.geQuizStorage();this.getQuizData();geQuizStorage() {this.quizStorage.getAnsw

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

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

Share Improve this question edited Jul 28, 2016 at 3:09 Patrioticcow asked Jul 27, 2016 at 6:28 PatrioticcowPatrioticcow 27.1k76 gold badges221 silver badges339 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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;
    });
}

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 plete.

 Observable.forkJoin([this.getQuizData(),this.geQuizStorage()])
  .subscribe(data => {
     console.log(data[0], data[1]);
     //both call succeeded
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1741937323a4374537.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信