繁体   English   中英

为什么我会收到“Uncaught(in Promise)”错误呢?

[英]Why am I getting “Uncaught(in Promise)” error with then?

then我有一个链条:

 ngOnInit() { this.contentfulService.getExhibits().then(exhibits => this.exhibits = exhibits).then(exhibits => {console.log("0", exhibits[0])}).then(exhibits => {console.log("1", exhibits[1])}); }

我收到错误Uncaught (in promise):在第二个console.log 我想不通这是为什么? 谢谢!

这里有几个问题:

您已分配this.exhibits = exhibits ,但没有返回任何东西。 因此,在下一个.then() exhibits无法访问,从而导致问题。 您可以像这样返回它:

.then(exhibits => {
    this.exhibits = exhibits
    return exhibits
})

虽然这可能不需要,因为您没有在任何地方使用this.exhibits 因此,您可以简单地退回exhibits ,例如:

.then(exhibits => exhibits)

虽然这也是不必要的,您可以简单地删除它并访问exhibits数组,例如:

this.contentfulService.getExhibits()
  .then(exhibits => {
    if(exhibits && exhibits.length){
      console.log("0", exhibits[0] || {})
      console.log("1", exhibits[1] || {})
    }       
  })

或者,如果您在其他地方使用this.exhibits ,那么您可以使用:

this.contentfulService.getExhibits()
  .then(exhibits => {
    this.exhibits = exhibits
    return exhibits
  })
  .then(exhibits => {
    if (exhibits && exhibits.length) {
      console.log("0", exhibits[0] || {})
      console.log("1", exhibits[1] || {})
    }
  })

此外,在进行 ajax 调用时,始终使用适当的错误处理,即catch ,即使在 ajax 调用在链中失败后,这对于完成新操作也很有用,例如:

this.contentfulService.getExhibits()
  .then(exhibits => {
    this.exhibits = exhibits
    return exhibits
  })
  .then(exhibits => {
    if (exhibits && exhibits.length) {
      console.log("0", exhibits[0] || {})
      console.log("1", exhibits[1] || {})
    }
  }).catch((error) => {
    console.error("Error: " + error);
  })

您不会从第一个.then到第二个返回任何东西,因此您的第二个.then中不会存在exhibits (第三个中也不存在)。

您应该从第一个.then中返回它,或者从this.exhibits中记录它。

像这样的东西:

ngOnInit() {
  this.contentfulService.getExhibits()
    .then(exhibits => {
      this.exhibits = exhibits
      return exhibits
    })
    .then(exhibits => {
      console.log("0", exhibits[0])
      return exhibits
    })
    .then(exhibits => {
      console.log("1", exhibits[1])
    });
}

或者更好

ngOnInit() {
  this.contentfulService.getExhibits()
    .then(exhibits => this.exhibits = exhibits)
    .then(exhibits => console.log("0", this.exhibits[0]))
    .then(exhibits => console.log("1", this.exhibits[1]));
}

暂无
暂无

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

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