【问题标题】:Angular2 promise - returning functions that already return a promiseAngular2 Promise - 返回已经返回 Promise 的函数
【发布时间】:2017-07-25 10:55:32
【问题描述】:

我编写了以下函数 - 我正在尝试返回现有的 promise 函数,而无需将它们包装在自定义 promise 中:

doAuthWithPrompt(): Promise <any> {
      this.getUser() // returns promise
      .then (user => {
        if (user == undefined) {
          this.promptForPassword() // returns promise
          .then (data => {
            return this.doAuth(data.email, data.password); // returns promise
          })
        }
        else {
            return this.doAuth(user.email, user.password) // returns promise
          };

      })
      .catch (e => {return Promise.reject(false);}) 

  }

我在 IDE(Visual Studio 代码)中遇到的错误是:

[ts] 声明类型既不是“void”也不是“any”的函数必须 返回一个值。

定义doAuthWithPrompt 时我遗漏了什么?谢谢。

【问题讨论】:

  • 你需要return this.getUser().then..
  • @echonax 为什么不将其发布为答案?
  • @user1361529 哦,我没有看到链式承诺,你也应该这样做。
  • @echonax ,我无可救药。我跟进了你的 cmets - 抱歉:p
  • @echonax 这样做:)

标签: angular


【解决方案1】:

您还需要返回包装器 Promise 及其链式承诺:

doAuthWithPrompt(): Promise <any> {
      return this.getUser() // returns promise
        .then (user => {
           if (user == undefined) {
             return this.promptForPassword() // returns promise
               .then (data => {
                 return this.doAuth(data.email, data.password); // returns promise
               })
           } else {
             return this.doAuth(user.email, user.password) // returns promise
           }    
      })
      .catch (e => {return Promise.reject(false);})     
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-23
    • 2020-06-20
    • 1970-01-01
    • 2021-10-18
    相关资源
    最近更新 更多