Thomas
Thomas

Reputation: 8849

ES6 Promise polyfill based on jQuery Deferred

I recently downloaded a library that uses ES6 Promises. Since I want to deploy to browsers which don't support Promises I also downloaded a polyfill.

Since I've got jQuery included anyway I thought about writing a polyfill for Promise which internally uses jQuery's Deferred.

I wrote this simple polyfill which is enough for my specific use case:

    window.Promise = function(cb){
        var promise = $.Deferred();

        cb(promise.resolve, promise.reject);

        return promise.promise();
    };

The problem with this is that it doesn't cover the whole specification (thinks like Promise.all() are missing).

Before I invest a lot of time into this I'd like to know if it is possible to write a full polyfill for Promise using jQuery's Deferred. Or are there some features which can't be replicated?

Upvotes: 4

Views: 2029

Answers (1)

Bergi
Bergi

Reputation: 664385

things like Promise.all() are missing

Promise.all can be more or less replicated by using $.when. Promise.race can be replicated by creating a deferred whose resolve/reject methods are attached to all input promises.

The problem with this is that it doesn't cover the whole specification

No. The parts that are not covered could easily be added. The real problem is that the existing parts of the jQuery Deferred implement do not comply with the specification - see Problems inherent to jQuery $.Deferred (jQuery 1.x/2.x)

Before I invest a lot of time into this I'd like to know if it is possible to write a full polyfill for Promise using jQuery's Deferred. Or are there some features which can't be replicated?

Everything can be replicated, but you'd need to monkeypatch enough in the Deferred implementation that you are better of just using one of the existing polyfills. If you really want to create your own, you might base it on a jQuery.Callbacks("once memory").

Upvotes: 3

Related Questions