2017-09-25 253 views
0

我希望我的抓取請求具有某種類型的重試系統,如果某些重試系統基於響應的HTTP代碼(例如:不是200)而失敗。它看起來是這樣的:有什麼方法可以進行遞歸獲取請求嗎?

fetch('someURLWithAJSONfile/file.json') 
     .then(function (res) { 
      console.log(res.status); 
      if (res.status !== 200) { 
       console.log("There was an error processing your fetch request. We are trying again."); 

// Recursive call to same fetch request until succeeds 

      } else { 
       return res.json(); 
      } 
     }).then(function (json) { 
     data = json; 
    }).catch(function (err) { 
     console.log(`There was a problem with the fetch operation: ${err.message}`); 
    }); 

有沒有把自定義的無極裏面的讀取請求,並使其調用自身檢查其HTTP響應狀態後一種方式?

+0

當然有。這只是一個承諾,可以鏈接和嵌套。請向我們展示您的嘗試代碼。 – Bergi

+0

'data = json;'是[什麼都行不通](https://stackoverflow.com/q/23667086/1048572) – Bergi

回答

1

您可以通過將您的調用包裝到一個命名函數中來獲取該函數,該命名函數返回fetch創建的承諾。試想一下:

function fetchWithRetry(url, retryLimit, retryCount) { 
    retryLimit = retryLimit || Number.MAX_VALUE; 
    retryCount = Math.max(retryCount || 0, 0); 
    return fetch(url).then(function (res) { 
     console.log(res.status); 
     if (res.status !== 200 && retryCount < retryLimit) { 
      console.log("There was an error processing your fetch request. We are trying again."); 
      return fetchWithRetry(url, retryLimit, retryCount + 1); 
     } else { 
      return res.json(); 
     } 
    }); 
} 

fetchWithRetry('someURLWithAJSONfile/file.json', 10).then(function (json) { 
    data = json; 
}).catch(function (err) { 
    console.log(`There was a problem with the fetch operation: ${err.message}`); 
}); 

此代碼封裝您現有的呼叫,並採取關閉範圍的優勢,以維持重試次數限制和數量這兩者都是可選的。然後,您可以使用URL調用fetchWithRetry函數,就像您之前調用的提取函數一樣。如果你沒有通過重試限制,它將繼續無休止地。最後的retryCount變量實際上僅用於遞歸目的,並且意在在內部調用。

1

這裏是簡單的ES6解決方案(因爲您使用的是fetch)。 limit選項表示您想要嘗試請求的次數。

var doRecursiveRequest = (url, limit = Number.MAX_VALUE) => 
    fetch(url).then(res => { 
    if (res.status !== 200 && --limit) { 
     return doRecursiveRequest(url, limit); 
    } 
    return res.json(); 
    }); 

doRecursiveRequest('someURLWithAJSONfile/file.json', 10) 
    .then(data => console.log(data)) 
    .catch(error => console.log(error)); 
相關問題