Skip to content

Instantly share code, notes, and snippets.

@codeboyim
Created November 29, 2015 06:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codeboyim/b1524687a921636a6ba7 to your computer and use it in GitHub Desktop.
Save codeboyim/b1524687a921636a6ba7 to your computer and use it in GitHub Desktop.
a solution to implementing chaining http://www.thatjsdude.com/interview/js2.html
function exec(fn){
var doneCallback, failCallback, fnCallback, fnEnded=false, _error, _data;
exec.done = function(cb){
doneCallback = cb;
if(fnEnded && !_error){
cb(_data);
}
return exec;
};
exec.fail = function(cb){
failCallback = cb;
if(fnEnded &&_error){
cb(_error);
}
return exec;
};
fnCallback = function(error, data){
_error = error;
_data= data;
if(failCallback && error){
failCallback(error);
}else if(doneCallback){
doneCallback(data);
}
fnEnded=true;
};
fnStarted=true;
fn(fnCallback);
return exec;
}
function slow(callback) {
setTimeout(function(){
if (Math.random() > 0.5) {
return callback("Error 417",null)
}
callback(null, {id:123})
},500);
}
exec(slow).done(function(data){
console.log(data);
}).fail(function(err){
console.log("Error: " + err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment