I am currently using fetch to retrieve data from a server. Unfortunately, I am facing issues with setting a timeout for the fetch request in case the server does not respond.
This is my global fetchData class:
fetchGetResp(url, token) {
return fetch(url, {
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
})
// .then(ApiUtils.checkStatus)
.then(response =>
response.json()
)
.then(responseJson => {
return responseJson
})
.catch(error => {
// console.log(error.headers._bodyText.status);
console.log('touching undefined catch');
return undefined;
});
}
Here is the Javascript class where I am utilizing the fetchData function:
let resp = fetchData.fetchGetResp(restUrl, userToken);
resp.then(responseJson => {
// console.log(res);
if (responseJson !== '' && responseJson !== undefined) {
}
else {
console.log(responseJson);
try {
}
catch (error) {
alert(error.message);
console.log(error + 'from js file');
}
}
// Some if statement
else {
alert('Unable to Process.please try again');
}
})
.catch(error => {
alert(error.message + "Please try again after sometime");
});
Please provide guidance on how to implement a timeout feature based on my current approach detailed above.