Skip to content

Instantly share code, notes, and snippets.

@kylehg
Last active August 29, 2015 13:55
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 kylehg/8750006 to your computer and use it in GitHub Desktop.
Save kylehg/8750006 to your computer and use it in GitHub Desktop.
###
# Call a Node-style async function and return a promise.
#
# @param {function} fn A function that accepts a Node-style callback.
# @param {...*} var_args A variable number of arguments to pass to the Node function.
# @return {Promise}
###
q = (fn, args...) -> new Promise (resolve, reject) ->
cb = (err, vals...) ->
if (err)
reject(err)
else if (vals.length > 1)
resolve(vals)
else
resolve(vals[0])
args.push(cb)
fn.apply(null, args)
/**
* Call a Node-style async function and return a promise.
*
* @param {function} fn A function that accepts a Node-style callback.
* @param {...*} var_args A variable number of arguments to pass to the Node function.
* @return {Promise}
*/
function q(fn, var_args) {
var args = [].slice.call(arguments, 1)
return new Promise(function (resolve, reject) {
function cb(err, val) {
if (err) {
reject(err)
} else if (arguments.length > 2) {
resolve([].slice.call(arguments, 1))
} else {
resolve(val)
}
}
args.push(cb)
fn.apply(null, args)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment