I am creating a node module and I want to be able to support both node callback and Promise APIs. The library that I hear the best things about (mainly that is it the fastest) is bluebird. So after reading some docs and looking at some other libraries that are using bluebird, I thought this would be the cleanest way to get a method to support both node callback and Promise APIs:
this.isAllowed = function(role, resource, permission, callback) {
var isAllowedAsync = bluebird.promisify(isAllowed);
return isAllowedAsync(role, resource, permission).nodeify(callback);
};
However with this code, the callback is never executed. After some more research, I tried this:
this.isAllowed = function(role, resource, permission, callback) {
return new bluebird(function (resolve, reject) {
resolve(isAllowed(role, resource, permission));
}).nodeify(callback);
};
With that code, both the node callback and Promise API works.
For reference, this is the isAllowed method:
var isAllowed = function(role, resource, permission) {
if(!lists[role] || !lists[role][resource]) {
return false;
}
return lists[role][resource].indexOf(permission) !== -1;
};
Am I doing something wrong in the first code example or is the second example the real way of getting what I am looking for?