Created
June 24, 2016 01:15
-
-
Save nijikokun/31f9423bd6becf10612a43e74437c5f9 to your computer and use it in GitHub Desktop.
< 35 line promisify that works in browsers and node.js
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
function pify (method, context) { | |
var resolver, rejector | |
var error, success | |
var done = false | |
var promise = { | |
then: function (a) { | |
if (!done && success != null) done = true, a(success); else resolver = a | |
return { catch: promise.catch } | |
}, | |
catch: function (a) { | |
if (!done && error != null) done = true, a(error); else rejector = a | |
return { then: promise.then } | |
} | |
} | |
var next = function (a, b) { | |
if (resolver && a != null) return (done = true) && resolver(a); else error = a | |
if (rejector && b != null) return (done = true) && rejector(b); else success = b | |
if (resolver && rejector) return resolver(b) | |
} | |
return function wrapper () { | |
var args = cloneArguments(arguments) | |
args.push(next) | |
method.apply(context || null, args) | |
return promise | |
} | |
} | |
function cloneArguments (arg, begin, end) { | |
for (var i = 0, len = arg.length, args = new Array(len); i < len; ++i) args[i] = arg[i] | |
return args = args.slice(begin || 0, end || undefined) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment