【问题标题】:How to break axios promise with conditional?如何用条件打破 axios 承诺?
【发布时间】:2018-02-06 22:28:43
【问题描述】:

在一个 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)

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

【问题讨论】:

  • then回调中添加括号{}
  • @alexmac 你能详细说明一下吗?我是 js 的新手。
  • 你身边没有函数表达式if statement。

标签: javascript promise vue.js axios


【解决方案1】:

您的代码中的问题是您的 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,验证它是否已定义并且它的长度等于零):

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

【讨论】:

  • 这会导致Uncaught (in promise) Error: end of pagination 即使在第一页。所以我想条件需要重写。
  • 你确定jokes在第一页不是空的吗?在 then 回调的顶部添加 console.log(jokes)
  • 是的,第 6 页有笑话。
  • 顺便说一句,在fetchData 的顶部增加页面,所以它从 1(如果它是 0)开始,而不是从 0。
  • console.log(jokes) 打印或不打印?
【解决方案2】:

你必须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")
      } 
    }
})

【讨论】:

  • 这消除了错误。但是我仍然得到最后一页什么都没有,这正是我想要避免的。知道怎么做吗?
  • @Karlom,是的,只需返回第一个 then 中的数据。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-23
  • 2020-02-23
  • 1970-01-01
  • 2023-04-03
  • 2015-06-12
相关资源
最近更新 更多