繁体   English   中英

在另一个承诺中解决承诺

[英]Resolve promise inside another promise

我是Promise的新手,在掌握如何将两个Promise组合在一起时遇到了一些麻烦。 我有一个函数,可以解决诺言并完成一些任务:

loginService (context, credentials) {
  context.$http.post(LOGIN_URL, credentials, { emulateJSON: true}).then(response => {
    this.user.authenticated = true
    localStorage.setItem(TOKEN_STORAGE_NAME, response.body[TOKEN_NAME])
  }).catch(response => {
    context.error = response.body
  })
},

我想修改上面的代码,以便可以执行以下操作:

login () {
  this.submitButtonLoading = true
  loginService(this, this.credentials).then(response => {
    this.submitButtonLoading = false
    // Do something else here.
  }).catch(response => {
    this.submitButtonLoading = false
    // Do something else here.
  })
}

处理此问题的正确方法是什么?

loginService 返回promise ,然后可以保持链接:

loginService (context, credentials) {
  return context.$http.post(LOGIN_URL, credentials, { emulateJSON: true})
    .then(response => {
      this.user.authenticated = true
      localStorage.setItem(TOKEN_STORAGE_NAME, response.body[TOKEN_NAME])
    })
    .catch(response => {
      context.error = response.body
    })
}

login () {
  this.submitButtonLoading = true
  loginService(this, this.credentials)
    .then(_ => {
      this.submitButtonLoading = false
      // ...
    })
}

请注意,无论调用成功与否, login中的then()函数将始终执行。

为了使loginService成为一个承诺,只需在函数内部返回Promise 请确保在函数完成时调用resolve和/或reject

在您的示例中,您可以:

var loginService = function(context, credentials) {
  return new Promise( (resolve, reject) => {
    context.$http.post(LOGIN_URL, credentials, {emlateJSON: true})
      .then(response => {
        if (success) {
          this.user.authenticated = true
          resolve(this.user)
        } else {
          reject(new Error('Log in failed'))
        }
      })
      .catch(err => {
        reject(err)
      })
    })
 }

现在可以了。

注意,整个函数实际上只是返回一个大Promise。 还要注意成功或失败是如何解决或拒绝的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM