[英]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.