Skip to content

Instantly share code, notes, and snippets.

@protometa
Last active August 29, 2015 13:56
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 protometa/9236780 to your computer and use it in GitHub Desktop.
Save protometa/9236780 to your computer and use it in GitHub Desktop.
Async promises within sync code hack with promisizer
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