Reputation: 311
Here is my current code , which is calling api and will do something
function callApiAjax(url,token){
var settings = {
"async": true,
"crossDomain": true,
"url": url,
"method": "GET",
"headers": {
"token": token,
}
};
var callAPI = $.ajax(settings);
callAPI.done(function(){
doSomethingWhenSuccess();
});
callAPI.fail(function(){
doSomethingWhenFail();
});
}
It works but sometimes the token will be expired. I have another api that can update the token. So I want to add another api into the fail function. Could I do something like that?
function callApiAjax(token,retry) {
var settings = {
"async": true,
"crossDomain": true,
"url": url,
"method": "GET",
"headers": {
"token": token,
}
};
var callAPI = $.ajax(settings);
callAPI.done(function () {
doSomethingWhenSuccess();
});
callAPI.fail(function () {
if(retry){
var updateTokenSetting = {
"async": true,
"crossDomain": true,
"url": url,
"method": "GET",
"headers": {
"token": token,
}
};
var updateToken = $.ajax(updateTokenSetting);
updateToken.done(function (response) {
//Set the original settings.headers.token to response.data.token;
//Redo the "CallAPI" ajax Call Once
});
updateToken.fail(function () {
doSomethingWhenFail();
});
}else{
doSomethingWhenFail();
}
});
}
I don't want to copy the settings in the fail function because I think that would be too complex and difficult to read but I don't know how to update only the token and redo the ajax call only one time.
Have any idea how to solve my problem?
Upvotes: 0
Views: 120
Reputation: 101
No you cant anything you have to call token api into fail function. But you can reorganize your code statments like this.
function callApiAjax(token,retry) {
var settings = {
"async": true,
"crossDomain": true,
"url": url,
"method": "GET",
"headers": {
"token": token,
}
};
var callAPI = $.ajax(settings);
callAPI.done(function () {
doSomethingWhenSuccess();
});
callAPI.fail(function () {
if(retry){
var updateToken = $.ajax(settings);
updateToken.done(function (response) {
//Set the original settings.headers.token to response.data.token;
//Redo the "CallAPI" ajax Call Once
});
updateToken.fail(function () {
doSomethingWhenFail();
});
}else{
doSomethingWhenFail();
}
});
}
Upvotes: 0
Reputation: 22474
You can simply do something like this:
updateToken.done(function(response){
callApiAjax(response.data.token, false);
}
Upvotes: 2