Created
November 29, 2015 06:43
-
-
Save codeboyim/b1524687a921636a6ba7 to your computer and use it in GitHub Desktop.
a solution to implementing chaining http://www.thatjsdude.com/interview/js2.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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