Javascript 如何打破axios承诺的条件?

Javascript 如何打破axios承诺的条件?,javascript,promise,vue.js,axios,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.jo

在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;    
  };
我想停止渲染空
笑话
,如果响应为空,则中断函数。正如您在关于ve的代码中所看到的,我在另一个中添加了一个条件,但在
if
中出现了错误:

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

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

您必须
附加
回调
函数,然后
承诺

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;    
}
或者使用
箭头
函数和
包装
带有
{}
的条件

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

代码中的问题是
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")
  }
})
另一个问题是,您定义了一个额外的
回调,然后
回调,并错误地验证
笑话
数组是否为空(而不是
this.jokes.length==null
,验证它是否已定义且长度等于零):


中添加括号
{}
,然后在
回调中添加括号。@alexmac您能详细说明一下如何操作吗?我是js新手。您周围没有函数表达式
if
语句。这将删除错误。但我仍然得到了最后一页,其中没有任何内容,这正是我想要避免的。知道怎么做吗?@Karlom,是的,只需先返回
然后返回
。这会导致
未捕获(承诺中)错误:分页结束
,甚至在第一页。所以我想条件需要重写。你确定第一页的
笑话
不是空的吗?在callback的顶部添加
console.log(笑话)
。是的,在第6页之前会有笑话。顺便说一句,在
fetchData
的顶部,您会增加页面,因此它从1开始(如果是0),而不是从0开始。
console.log(笑话)
是否打印一些内容?
.then(response => { 
   let jokes = response.data;
   if (!jokes || jokes.length === 0) {
     throw new Error("end of pagination");
   }
   this.jokes = jokes;
});