A co-worker and I were recently talking about Promises in es6. He was suprised to see the Q style promises not adopted in es6, so I set out to show him he could add a similar API if he wanted.

The main difference is that Q passes around an object that has resolve/reject methods while promises in es6 take a function whos arguments are resolve and reject. Here's an example of both.

Q Example

var deferred = Q.defer();

setTimeout(function () {  
    deferred.resolve('success');
}, 1000);

deferred.promise.then(function () {  
    // success
}, function () {
    // error
});

es6 Example

var promise = new Promise(function (resolve, reject) {  
    setTimeout(function () {
        deferred.resolve('success');
    }, 1000);
});

promise.then(function () {  
    // success
}, function () {
    // error
});

Solution

All I'm going to add to the es6 implementation is a resolve and reject method. It's not identical to the Q styles promises which has a separate promise attribute.

We are going to access this new API via the qDefer function. Here is the implementation:

var qDefer = function () {  
    // store references to the resolve and reject callbacks
    var cachedResolve;
    var cachedReject;

    Promise.prototype.reject = function () {
        cachedReject.apply(this, arguments);
    };

    Promise.prototype.resolve = function () {
        cachedResolve.apply(this, arguments);
    };

    // return a new promise, saving the callback functions
    return new Promise(function (resolve, reject) {
        cachedResolve = resolve;
        cachedReject = reject;
    });
}

Example Usage

var deferred = qDefer();

setTimeout(function () {  
    deferred.resolve('success');
}, 1000);

deferred.then(function (message) {  
    // success
    // message === "success"
}, function () {
    // error
});

Demo: http://jsfiddle.net/andrewjmead/pdrgg/