javascript - 第二个 .then() on promise 被调用时数据未定义

标签 javascript angular typescript promise rxjs

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

这个 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);
      })
  }

当我在另一个使用此 signIn 方法的类(class)时,问题就出现了。 promise 中的响应现在为空。当我从函数本身省略 promise 时,返回的 promise 的 .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() 包含一个值,但返回给出的 promise 在它的 .then() 中没有值?如果有什么令人困惑的地方,我很乐意澄清。谢谢:)

最佳答案

正如@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
});

关于javascript - 第二个 .then() on promise 被调用时数据未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44491352/

相关文章:

javascript - 通过 Ajax 的 MYSQL 数据库到 Highcharts 图表

javascript - 在 Nest JS 中模拟 HTTP 拦截器

reactjs - 当我尝试传递另一个 prop 时,为什么 typescript 会在我的 HOC 中触发一个使用 rest props 的错误?

html - Angular 2+ 的虚拟滚动

javascript - sublime text 3 中 typescript 的构建系统不起作用

来自数组的函数时的 Javascript 作用域问题

javascript - flatMap如何限制并发?

javascript - 从文件 express js 提供 json

javascript - 刷新后清除 Angular 2 LocalStorage

angular - 输入焦点时如何隐藏错误消息?