鍍金池/ 問答/HTML/ axios 異步請求后.then()后再接.then()要怎么寫

axios 異步請求后.then()后再接.then()要怎么寫

doctorComments(this.$route.params.hid, this.$route.params.fid, this.doctorHisId, this.createdon, this.pageno, 5)  //1.axios請求數(shù)據(jù)
.then(d => {//2.處理數(shù)據(jù)
  let dc = new Array()
  for(let i=0;i<d.list.length;i++){
    dc[i] = {doctorComments:d.list[i],isZhanshiComment:false}
  }
  this.doctorComments = this.doctorComments.concat(dc);
  this.$refs.scroller.donePullup();
  
})
.then(()=>{//3.調(diào)用方法
    this.$options.methods.compareHeightComment();
})

3.里面調(diào)用的方法需要doctorcommts這個數(shù)組的信息。想要用js promise的相關(guān)方法去鏈式調(diào)用,但是我這么寫3里面的方法仍然取不到2里面設(shè)置的數(shù)據(jù)。取2里面的數(shù)組長度length是undfined。
vue.js.
各位大神,3里面的方法怎么才能取到2設(shè)置好后的值。

回答
編輯回答
九年囚

return給你個例子 箭頭函數(shù)后面有大括號要加return

Promise.resolve(1).then(v=> {
    console.log(v)//1
    return 123;
}).then(v => {
    console.log(v)//123
})
doctorComments(this.$route.params.hid, this.$route.params.fid, this.doctorHisId, this.createdon, this.pageno, 5)  //1.axios請求數(shù)據(jù)
.then(d => {//2.處理數(shù)據(jù)
  let dc = new Array()
  for(let i=0;i<d.list.length;i++){
    dc[i] = {doctorComments:d.list[i],isZhanshiComment:false}
  }
  this.doctorComments = this.doctorComments.concat(dc);
  this.$refs.scroller.donePullup();
  return this.doctorComments;
})
.then((v)=>{//3.調(diào)用方法 
    console.log(v);v就是this.doctorComments這個數(shù)組
})
2018年9月21日 22:41
編輯回答
舊城人

后來查明原因。this在then之后調(diào)用的方法里指向不是當前vue實例。如果在調(diào)用的方法里面使用this,就會一直找不到值。按照李十三大神的用法在promise之前傳入當前vue實例。

let that = this;//promise 之外
...//中間的其他邏輯
.then() //鏈式調(diào)用
.then(func(that){...}); //調(diào)用其他方法


//其他方法
func(that){
that.xxx   //vue的各類操作。
that.xxx
}

調(diào)用的方法里面使用這個that實例。
最終嚴格來講是作用域的問題。

2017年7月12日 07:28