1

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.

Tedd
  • 111
  • 4

1 Answers1

2

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.

Esailija
  • 5,364
  • 1
  • 19
  • 16
  • Considering the popularity of Bluebird, a brief explanation of this can be added to the documentation. What do you think? – thefourtheye Apr 14 '15 at 14:29
  • So for clarity it isn't the use of `return new Promise` that is the anti pattern, it is when you already have a promise/thenable object or a callback that can be promisified: which means you're wrapping a promise in a promise. – Tedd Apr 15 '15 at 08:21