javascript - fetch api retry if http request fails -
i'm using browser's native fetch api network requests. using whatwg-fetch polyfill unsupported browsers.
however need retry in case request fails. there npm package whatwg-fetch-retry found, haven't explained how use in docs. can me or suggest me alternative?
from official fetch docs :
fetch('/users') .then(checkstatus) .then(parsejson) .then(function(data) { console.log('succeeded', data) }).catch(function(error) { console.log('request failed', error) })
see catch? trigger when fetch fails, can fetch again there example.
have @ promises https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/promise
edit: add working example should return result. have tried in chrome (v.60.0) , didn't use polyfill nor package mention (after reading docs seems fork fetch polifyll).
function fetchretry(url, delay, limit, fetchoptions = {}) { return new promise((resolve,reject) => { function success(response) { resolve(response); } function failure(error){ limit--; if(limit){ settimeout(fetchurl,delay) } else { // time failed real reject(error); } } function finalhandler(finalerror){ throw finalerror; } function fetchurl() { return fetch(url,fetchoptions) .then(success) .catch(failure) .catch(finalhandler); } fetchurl(); }); } fetchretry('https://www.google.es',1000,4) .then(function(response){ if(!response.ok){ throw new error('failed!'); } return response; }) .then(function(response){ console.log(response); }) .catch(function(error){ console.log(error); });
haven't tested if retry attempts return response suppose do.
edit: found package replaces fetch api i'm not pretty sure that, https://www.npmjs.com/package/fetch-retry (there 2 more packages 1 in first google results page fetch-retry...)
Comments
Post a Comment