Skip to content

Instantly share code, notes, and snippets.

@hpstuff
Last active August 29, 2015 14:10
Show Gist options
  • Save hpstuff/1a86e480894af28532a4 to your computer and use it in GitHub Desktop.
Save hpstuff/1a86e480894af28532a4 to your computer and use it in GitHub Desktop.
Clean Code example
function getUser(){
var _this = this;
var ajax = new Ajax();
var header = { 'Authorization': this.tokenType+' '+this.accessToken };
ajax.setHeaders(header);
return new Promise(function(resolve, reject){
if(_this.userData){
resolve({data: _this.userData});
}else{
ajax.get(_this.userUrl).then(function(res){
_this.userData = res.data;
resolve(res);
}, function(err){
if(err.data.error === "invalid_token"){
_this.renewToken().then(function(data){
_this.userData = null;
_this.getUser().then(function(data){
resolve(data);
}, function(){
reject(err);
})
},function(err){
reject(err);
});
}else{
reject(err);
}
});
}
});
}
function getUser(){
var _this = this;
var ajax = new Ajax();
var header = { 'Authorization': this.tokenType+' '+this.accessToken };
ajax.setHeaders(header);
return new Promise(function(resolve, reject){
if(_this.userData){
resolve({data: _this.userData});
return;
}
ajax.get(_this.userUrl).then(function(res){
_this.userData = res.data;
resolve(res);
}, function(err){
if(err.data.error !== "invalid_token"){
reject(err);
return;
}
_this.renewToken().then(function(data){
_this.userData = null;
_this.getUser().then(function(data){
resolve(data);
}, function(){
reject(err);
})
},function(err){
reject(err);
});
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment