Skip to content

Instantly share code, notes, and snippets.

@Zodiase
Last active October 11, 2016 22:41
Show Gist options
  • Save Zodiase/267f20fd4580bb7ecccb0fd352d1941c to your computer and use it in GitHub Desktop.
Save Zodiase/267f20fd4580bb7ecccb0fd352d1941c to your computer and use it in GitHub Desktop.
// 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