Last active
August 29, 2015 13:56
-
-
Save protometa/9236780 to your computer and use it in GitHub Desktop.
Async promises within sync code hack with promisizer
This file contains 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
Q = require 'q' | |
promisize = (fn, args... ) -> | |
promises = [] | |
getpromises = ( p ) -> | |
promises.push( p ) | |
null | |
giveresults = () -> | |
promises.shift() | |
len = args.length | |
args[len] = getpromises | |
try # this could be iterated serval times to resolve any type errors | |
fn.apply(null,args) | |
# console.log promises.length | |
Q.all( promises ) | |
.then -> | |
args[len] = giveresults | |
fn.apply(null,args) | |
# | |
# example... | |
# | |
promiseB = -> # gives a promise | |
Q.fcall () -> | |
return 2 | |
# sync function with promise inside | |
# prep sync fuction by adding promise arg and calling all promises with it | |
# it's probably best if this sync function doesn't have serious side-effects | |
syncfunc = (c, promise) -> | |
a = 1 | |
b = promise( promiseB() ) # promise here | |
return a + b + c | |
# promisize sync function f | |
promisize( syncfunc, 3 ) | |
.then (res) -> | |
console.log res # 6 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment