Fetch API Request Timeout

Fetch API request timeout?

Edit 1

As pointed out in comments, the code in the original answer keeps running the timer even after the promise is resolved/rejected.

The code below fixes that issue.

function timeout(ms, promise) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
reject(new Error('TIMEOUT'))
}, ms)

promise
.then(value => {
clearTimeout(timer)
resolve(value)
})
.catch(reason => {
clearTimeout(timer)
reject(reason)
})
})
}



Original answer

It doesn't have a specified default; the specification doesn't discuss timeouts at all.

You can implement your own timeout wrapper for promises in general:

// Rough implementation. Untested.
function timeout(ms, promise) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
reject(new Error("timeout"))
}, ms)
promise.then(resolve, reject)
})
}

timeout(1000, fetch('/hello')).then(function(response) {
// process response
}).catch(function(error) {
// might be a timeout error
})

As described in https://github.com/github/fetch/issues/175
Comment by https://github.com/mislav

Fetch times out after 2 minutes

I used @jfiend00's suggestion and redesigned my application to use a WebSocket connection. I no longer run into timeout issues as long as I have occasional ping/pong messages sent between the server and client to keep the connection alive.

How to stop polling using timeout in fetch request while adding intervals

Your return statement can't possibly work because this function is recursive - it'll never get there if the fetch keeps failing. What about just adding an index to track how many times you've retried subscribe?

const addDelay = (timeout) =>
new Promise((resolve) => setTimeout(resolve, timeout));

const failed = 0;

export const myReport = () => async (dispatch) => {
dispatch({
type: constants.DOWNLOAD_REPORT_REQUEST,
});

let url = `/admin/dashboard/report.js?project_id=${projectId}&tool_id=${toolId}`;

try {
const subscribe = async (uri) => {
let response = await fetch(uri, {
method: 'GET',
headers: {
'content-type': 'application/json',
'x-api-token': `Bearer ${token}`,
},
});
const resBody = await response.json();
if (resBody.status === 'success') {
window.location.href = resBody.url;
dispatch({ type: constants.DOWNLOAD_REPORT_SUCCESS });
} else {
if (failed >= 3) {
// whatever you want to do on fail
} else {
failed += 1;
await addDelay(5000);
await subscribe(url);
}
}
};
subscribe(url);
} catch (error) {
dispatch({
type: constants.DOWNLOAD_REPORT_FAILURE,
errorMessage: error.status,
});
}
};



Related Topics



Leave a reply



Submit