I have two fetch calls on my typescript code, one to get access token and other to call the actual API.
I need to set time out(1 second) for second API call. If timed out, a retry should be made and while retrying, access token should be retrieved again.
What is the best approach to achieve this?
CodePudding user response:
I think is it useful to just try and catch your code, then if the error you have is instance of TimeoutError or something like this it is depend on what package you are using, so call your function again for example, if your are using axios, it would be something like this
async function fn() {
const response = await axios.post("/auth/login");
// get your token here.
try {
const result = await axios.get("/second/api");
} catch (error) {
if (error.code === "ECONNABORTED") {
// just call your function again.
fn();
}
}
axios timeout error is defined by ECONNABORTED error code
DO NOTE that this function is going to call itself forever if there is always timeout error, so you could apply some mechanism to avios this, like storing number of tries in a variable
CodePudding user response:
You can wrap the 1 second timer into a promise and then use Promise.race to detrime which promise (timer or the actual request) resolves faster. If the timer expires faster then restart the process otherwise return the result of the api call:
async function run() {
const accessToken = await getAccessToken();
const retry = new Promise((resolve) => {
setTimeout(() => {
resolve('EXPIRED')
}, 1000)
});
const resp = apiCall(accessToken);
const result = await Promise.race([retry, resp]);
if (result === 'EXPIRED') {
return run();
}
return result;
}