Javascript – Correct usage of Bluebird promise

javascriptnode.jsperformance

This is related to this question on promise performance. The current top answer states that using new Promise is

an anti-pattern in bluebird

And that promisify should be used instead. I understand that promisifycan be used for functions that are using callbacks. But if I have my own code that I want to get a promise from how should this be done?

For example at the moment I have a function that performs a rest call and I use:

return new Promise(function (resolve, reject) {
    ...
    resolve(data);
    ...
    reject(err);
}

I can then use this with the normal .then(). So this is correct for ES6, but if performing it the way bluebird intends what is the correct implementation to be as efficient as possible? As I think that taking my code and changing it to be handled with callbacks simply to use promisify seems a bit nuts. Potentially I may have got the wrong end of the stick.

Best Answer

This question probably doesn't belong to programmers but

var request = function() {
    return new Promise(function(resolve, reject) {
      ...
      resolve(data);
      ...
      reject(err);
    }
};

Is of course much slower than

var request = promisify(function(callback) {
    ...
    callback(null, data);
    ...
    callback(err);
});

However, this isn't the anti-pattern. The anti-pattern is using new Promise when promisify or .then() would suffice. For instance, here request is most likely just using some other APIs that already are implemented as callbacks/promises. Then new Promise is an anti-pattern because you should just chain the existing promise or promisify the callback api and then chain from the promises returned.

Related Topic