Last active
December 25, 2015 03:09
-
-
Save togakangaroo/6907203 to your computer and use it in GitHub Desktop.
defr little flow control library to turn callback apis into promises
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
w = window | |
w.defr = (fnOrCtx, fnOrUndef) -> | |
ctx = if fnOrUndef then fnOrCtx else window | |
fn = if fnOrUndef then fnOrUndef else fnOrCtx | |
submittedArgs = null | |
getDeferredGenerator = (_.find(defr.conversions, (c)->c.canAdapt fn, ctx)?.adapt || defr.defaultConversion) | |
getDeferred = _.wrap getDeferredGenerator(fn, ctx), (fn, args...) -> | |
submittedArgs = _.toArray args | |
fn.apply @, args | |
_.compose ((d)-> d.fail (logResults "error", -> console.log this, "fn", fn, "ctx", ctx, "args", submittedArgs)), getDeferred | |
defr.conversions = [ | |
{ | |
canAdapt: (fn, ctx) -> fn instanceof FileReader | |
adapt: (reader) -> (startRead) -> | |
$.Deferred (d) -> | |
reader.onerror = reader.onabort = d.reject | |
reader.onloadend = (e, args...) -> d.resolve.apply @, (_.union [e.target.result], [e], args) | |
startRead(reader) | |
} | |
{ | |
canAdapt: (fn) -> (_.isArray fn) and _.all fn, (x) -> x.done && x.pipe && x.fail && x.then; | |
adapt: (deferreds) -> -> $.when.apply $, deferreds | |
} | |
] | |
defr.defaultConversion = (fn, ctx) -> (args...) -> | |
$.Deferred (d) -> | |
fn.apply ctx, (_.union args, [d.resolve, d.reject] ) | |
logResults = (text, continueWith) -> -> | |
w.logResults.last = ctx: @, args: (_.toArray arguments), text: text | |
(w.logResults.stack = w.logResults.stack || []).push w.logResults.last | |
console.log text||"", this, arguments | |
continueWith?.apply @, arguments |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment