【问题标题】:Second .then() on promise is getting called with data as undefined承诺的第二个 .then() 被调用,数据未定义
【发布时间】:2017-06-12 12:54:28
【问题描述】:

我在名为 accountManager 的服务中有一个函数,它返回如下所示的承诺:

这个 promise 上的 .then() 触发并打印出预期的响应。

  signIn(email:String,password:String):Promise<any>{
    return this.http.post('http://localhost:3000/api/signin',JSON.stringify({
      "email": email,
      "password": password
    }),{headers: this.headers})
      .toPromise()
      .then(res => {
      //**This is defined**
        console.log(res);
      })
  }

当我在另一个使用此登录方法的类中时,就会出现问题。承诺中的响应现在为空。当我从函数本身中省略承诺时,返回的承诺的 .then() 具有响应的值。

if (this.loginForm.valid === true){
  this.accountManager.signIn(this.email,this.password)
    .then(response =>{

    //**This .then has an undefined response when added on to the promise returned from the signIn function.**

      let body = JSON.parse(response._body)

      if (body.payload.success === true){
        this.router.navigate(['/']);
      }else{
        this.signInError = true;
      }
  })
    .catch(error=>{
      this.signInError = true;
    })

有谁知道为什么当 promise 被返回时 promise .then() 包含一个值,但 return 给出的 promise 在它的 .then() 中没有值?如果有什么令人困惑的地方,我很乐意澄清。谢谢:)

【问题讨论】:

  • console.log 通话后您没有返回res
  • 但是我不能返回它,因为我已经返回了函数,对吧?
  • 不,这是不对的。在 .then 回调中返回与在封闭函数中返回无关 - 从当前函数返回返回
  • 您的问题标题具有误导性 - 两个 .then 都被调用,否则您不会知道第二个中的响应未定义。那么
  • 感谢您的帮助!

标签: javascript angular typescript promise rxjs


【解决方案1】:

正如@cartant 所说,在console.log 调用之后您不会返回res。从 Promise 回调返回的值解析 Promise。

new Promise(function(resolve) {
    // this is almost equivalent 
    // to returning in promise callbacks
    resolve(3);
})
.then(function(res) {
   console.log(res); // logs 3  
   return 7;
})
.then(function(res) {
   console.log(res); // logs 7
   // no return, implicitly returns undefined
})
.then(function(res) {
   console.log(res); // logs `undefined`
});

返回值也可以是另一个 Promise,因为随后的 .then 回调将监听该 Promise 以解决:

new Promise(function(resolve) {
    // this is almost equivalent 
    // to returning in promise callbacks
    resolve(3);
})
.then(function(res) {
   return Promise.resolve(5);  // can create a Promise which resolves immediately
})
.then(function(res) {
   console.log(res); // logs 5
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    相关资源
    最近更新 更多