14

I use the Q library that supports the Promise specification well. But I also try to use the Promise class that has been implemented in Chrome not long ago (experimentally).

There's the defer function in Q that can be used for creating a non-fulfilled promise that can be resolved or rejected in the future.

I've implemented the same functionality using the native Promise presented in Chrome. Here's an example:

var defer = function() {
    var result = {};
    result.promise = new Promise(function(resolve, reject) {
        result.resolve = function(value) {
            resolve(value);
        };
        result.reject = function(value) {
            reject(value);
        };
    });
    return result;
};

var deferred = defer();
deferred.promise.then(function(value) {
    alert(value);
});
deferred.resolve(10);

I'm curious is there any design flaw in this solution such as performance slowdown or incorrectness.

j08691
  • 204,283
  • 31
  • 260
  • 272
shadeglare
  • 7,006
  • 7
  • 47
  • 59

2 Answers2

16

You are creating unnecessary function objects.

You can just do:

var defer = function() {
    var result = {};
    result.promise = new Promise(function(resolve, reject) {
        result.resolve = resolve;
        result.reject = reject;
    });
    return result;
};

Design flaw is doing this in the first place, native promises are useless if you are using Q.

Esailija
  • 138,174
  • 23
  • 272
  • 326
  • 2
    "Native promises are useless" - why? Wouldn't one expect better optimisations etc in them? – Bergi Feb 13 '14 at 18:54
  • 2
    First of all promise perf is useless on client side, secondly native promises are very slow (not unlike almost every other native implementation being slower than user implemented). Thirdly ES6 promises have very little functionality and are barely usable on real projects out of the box. – Esailija Feb 13 '14 at 19:03
  • @Bergi iirc at the moment native promises are faster than Q promises but slower than Bluebird promises - that's really not the concern like Petka said. The more bothering part is that they have worse stack traces than Bluebird promises :D – Benjamin Gruenbaum Feb 15 '14 at 15:37
5

See http://bluebirdjs.com/docs/benchmarks.html for benchmarks. There are some JSPerf benchmarks as well, however "for a reasonably fast promise implementations latency is going to be fully determined by the scheduler being used and is therefore not interesting to benchmark. JSPerfs that benchmark promises tend to benchmark latency."

gx0r
  • 4,682
  • 2
  • 23
  • 24