【问题标题】:Promises in Ionic 2 / Angular 2, how to?Ionic 2 / Angular 2 中的承诺,怎么做?
【发布时间】:2023-03-09 01:44:02
【问题描述】:

我有两个功能:

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

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

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

我正在尝试对这两个函数使用 Promise 并等到两个函数都完成,例如:

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

任何想法如何在 Ionic 2 / Angular 2 中做到这一点

【问题讨论】:

    标签: javascript angular angular-promise ionic2


    【解决方案1】:

    您可以使用 ES6 Promise 的 all 函数来做到这一点。无需外部库。

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

    你的函数应该返回 Promise 才能使它起作用,所以我建议进行以下修改:

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

    【讨论】:

    • 我不需要解决一些承诺并在我的 2 个函数中返回它吗?
    • 我错过了你的函数不返回承诺的部分......但你只需要让getQuizStoragegetQuizData 返回承诺。这可以通过在调用服务函数之前添加return 轻松完成。请参阅编辑后的答案。
    • 你能让他们返回数据吗?
    • 我正在这样做,但我有一个问题,如果请求失败,promise.all 进入拒绝函数但出现错误:未捕获(在承诺中)我在这里打开问题可以你帮帮我:stackoverflow.com/questions/44460438/…
    【解决方案2】:

    基本上,您不需要为您的服务调用创建另一个包装函数,只需返回一个数据(除非您有验证逻辑来​​验证数据)。然后通过传递 promises/observable'ssubscribe 方法在该 observable 上传递 Observable.forkJoin 中的这两个函数,等待它们完成。

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

    【讨论】:

      猜你喜欢
      • 2016-10-25
      • 2017-02-08
      • 2017-06-18
      • 2018-01-17
      • 2016-08-05
      • 1970-01-01
      • 1970-01-01
      • 2016-06-01
      • 1970-01-01
      相关资源
      最近更新 更多