Reputation: 404
I want to set a time limit for an axios
request to wait for a response
For example, I fired a request from the client then I would like to set the system to wait for only 8 seconds then show a request time out
Kindly see my axios
request below
executeJwtAuthenticationService(username, password) {
return axios.post(`${API_URL_LOCAL}`, {
username,
password,
});
}
How would I pattern it similar to this?
axios({
method: 'post',
url: '/user',
timeout: 8000, // Let's say you want to wait at least 8 seconds
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
})
Upvotes: 0
Views: 4571
Reputation: 40
Try Promise.race:
executeJwtAuthenticationService(username, password) {
const timeoutPromise = new Promise(resolve => {
const timeout = setTimeout(() => {
clearTimeout(timeout);
resolve('It took too long...');
}, 8000);
});
const request = axios.post(`${API_URL_LOCAL}`, {
username,
password,
});
return Promise.race([timeoutPromise, request]);
}
You'll probably want to add a similar promise timeout to 'catch' in case response takes long time and fails in the end. Read about race on MDN
Upvotes: 1
Reputation: 10520
If you trying to implement your axios.post
request with the inline version, so you just have to know, it will take configs as a separate object.
So your final code should be something like this:
axios.post(`${API_URL_LOCAL}`, {
username,
password,
}, {
timeout: 8000
});
NOTE: For more information you can read this.
Upvotes: 2