如何用条件打破axios承诺?

时间:2017-08-29 12:46:01

标签: javascript promise vue.js axios

在vue.js应用程序中,我有这个部分处理获取无限分页的提取数据:

fetchData() {
      this.loading = true
      this.page++;
      axios.get(this.BASE_URL + '/api/jokes/'+'?page='+this.page).then( response => 
            this.jokes = response.data)
           .then( if (this.jokes.length == null) {throw new Error("end of pagination")} )
           .catch(function (error) {
           });      
     document.body.scrollTop = document.documentElement.scrollTop = 0;
     this.loading = false;    
  };

如果响应为空,我想停止渲染空jokes并中断函数。正如您在代码中看到的那样,我在另一个中添加了条件,但在if上得到了错误:

Module build failed: SyntaxError: Unexpected token (169:20)

所以我想知道实现这个目标的正确方法是什么?

2 个答案:

答案 0 :(得分:3)

代码中的问题是您的then回调定义不正确。

.then(() => if (this.jokes.length == null) {throw new Error("end of pagination")})

您需要用括号{}包装它:

.then(() => {
  if (this.jokes.length == null) {
     throw new Error("end of pagination")
  }
})

另一个问题是,您定义了一个额外的then回调并且错误地验证jokes数组是空的(而不是this.jokes.length === null,验证它是否已定义,并且&# #39;长度等于零):

.then(response => { 
   let jokes = response.data;
   if (!jokes || jokes.length === 0) {
     throw new Error("end of pagination");
   }
   this.jokes = jokes;
});

答案 1 :(得分:1)

您必须attach callback功能then 承诺

fetchData() {
  this.loading = true
  this.page++;
       axios.get(this.BASE_URL + '/api/jokes/'+'?page='+this.page).then(function( response){
          this.jokes = response.data;
          return this.jokes;
       }).then(function(response){
          if (!response || response.length == 0) {
            throw new Error("end of pagination")
          } 
       }).catch(function (error) {

       });        
   document.body.scrollTop = document.documentElement.scrollTop = 0;
   this.loading = false;    
}

或使用arrow函数和wrap条件{}

.then(()=>{
      if (this.jokes.length == null) {
          throw new Error("end of pagination")
      } 
    }
})