Last active
October 11, 2016 22:41
-
-
Save Zodiase/267f20fd4580bb7ecccb0fd352d1941c to your computer and use it in GitHub Desktop.
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
// Omit the last argument (the callback) of the original function and use promise instead. | |
function wrapAsPromise (func) { | |
var expectedArgCount = func.length - 1; | |
return function () { | |
// Only the last argument (the callback) can be missing. | |
switch (true) { | |
case arguments.length < expectedArgCount: | |
throw new Error('Not enough arguments given. Expecting ' + expectedArgCount + '.'); | |
break; | |
case arguments.length < expectedArgCount: | |
throw new Error('Too many arguments given. Expecting ' + expectedArgCount + '.'); | |
break; | |
default: | |
// As expected. | |
break; | |
} | |
var _this = this, | |
_args = Array.prototype.slice.call(arguments); | |
return new Promise(function (resolve, reject) { | |
try { | |
func.apply(_this, _args.concat(function (err, result) { | |
if (err) { reject(err); } else { resolve(result); } | |
})); | |
} catch (err) { | |
reject(err); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment