2017-08-29 67 views
1

在vue.js的應用程序,我有這個部分,與無限的分頁取數據涉及:如何打破axios承諾與條件?

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,打破了該功能的響應是否爲空。正如你可以在代碼abouve看,我把其他有條件的話,但對if得到錯誤:

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

所以我不知道什麼是實現這一目標的正確方法是什麼?

+0

在'then'回調中添加括號'{}'。 – alexmac

+0

@alexmac能詳細說明一下嗎?我是新來的js的東西。 – Karlom

+0

你在if語句周圍沒有函數表達式。 – Bergi

回答

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; 
}); 
+0

這會導致'未捕獲(承諾)錯誤:分頁結束,即使在第一頁。所以我想有條件的需要重寫。 – Karlom

+0

你確定第一頁上的「笑話」不是空的嗎?在回調的頂部添加'console.log(笑話)'。 – alexmac

+0

是的,最開始有第6頁的笑話。 – Karlom

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") 
     } 
    } 
}) 
+0

這可以消除錯誤。但是我仍然看到最後一頁不包含任何內容,這正是我想要避免的。任何想法是怎麼做到的? – Karlom

+0

@Karlom,是的,只是返回第一個'然後'的數據。 –