Skip to content

Commit

Permalink
Fallback when AbortController is not available
Browse files Browse the repository at this point in the history
  • Loading branch information
FlorianCassayre committed Nov 18, 2021
1 parent 0e01bb1 commit b8d7463
Showing 1 changed file with 22 additions and 9 deletions.
31 changes: 22 additions & 9 deletions src/api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,28 @@ function buildURL(root, parameters) {

function timeoutFetch(url) {
return new Promise((resolve, reject) => {
const controller = new AbortController();
const signal = controller.signal;
const timer = setTimeout(() => {
controller.abort();
reject(new ErrorTimeout());
}, FETCH_TIMEOUT);
let controller = null;
try {
controller = new AbortController();
} catch(e) {
// AbortController not available (observed on Firefox ESR 52)
}

fetch(url, { signal })
let signal = null, timer = null;
if(controller !== null) {
signal = controller.signal;
timer = setTimeout(() => {
controller.abort();
reject(new ErrorTimeout());
}, FETCH_TIMEOUT);
}

fetch(url, signal !== null ? { signal } : undefined)
.then(result => result.json())
.then(value => {
clearTimeout(timer);
if(timer !== null) {
clearTimeout(timer);
}
if (value.code >= 200 && value.code < 400) {
resolve(value);
} else if (value.code === 503) {
Expand All @@ -40,7 +51,9 @@ function timeoutFetch(url) {
}
})
.catch(reason => {
clearTimeout(timer);
if(timer !== null) {
clearTimeout(timer);
}
reject(reason);
});
});
Expand Down

0 comments on commit b8d7463

Please sign in to comment.