Git Product home page Git Product logo

promise-polyfill's People

Contributors

2xaa avatar andarist avatar andrewiggins avatar benjamingr avatar calummacuisdean avatar dependabot[bot] avatar derappelt avatar dfahlander avatar dsergiu avatar gabibguti avatar goodluck42 avatar himanshu-27 avatar jamie5 avatar joseluisq avatar krinkle avatar limonte avatar lukasdrgon avatar pamplo avatar rosenfeld avatar spanic avatar taylorhakes avatar timvdlippe avatar vmihailenco avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

promise-polyfill's Issues

ES6 Promise compatible

The documentation status the lib is A+ Compliant, but is says nowhere it's compatible with ES6 Promise. Is it intended to be compatible? Is it 100% compatible? Is that tested? Please improve your documentation.

Question: Promise is undefined

Webpack + Typescript

  1. tsc
  2. webpack
  3. page loads with bundle.js

I am importing the polyfill like this at the top of my file in IE11
import Promise from 'promise-polyfill';

When the page is fully loaded, I check if Promise exists:

image

image

IE11: SCRIPT65535: Ungültiges aufrufendes Objekt.

function handle(self, deferred) {
    while (self._state === 3) {
      self = self._value;
    }
    if (self._state === 0) { // Exception!!!
      self._deferreds.push(deferred);
      return;
    }
    self._handled = true;
    Promise._immediateFn(function () {

Minified code IE8 error

ECMAScript 3 does not allow bare keywords in dot notation.
but promise.min.js has code like this

o.prototype.catch=function(e){return //...

It causes an error on IE8. "Expected identifier"

Issue with browserify

Trying to use your library in my project and faced with issue below in browserify.

Uncaught ReferenceError: Reflect is not defined 
    Promise.js:178(anonymous function) 
    Promise.js:178s _prelude.js:1
    (anonymous function) _prelude.js:1

The cause is that after compilation step browserify wraps every source file into:

module.exports = function() {
  "use strict";
  (source file)
};

In other words it forces to use strict mode where this is undefined. To solve the issue I just used

(function() {
  var global = this || window;
  ...
})(); 

Not sure if it's the best fix but it works.

Unexpected Token

Thanks for this!

When attempting to polyfill using:

import 'promise-polyfill/src/polyfill';

I get:

[14:48:13] Unexpected token (2:7) while parsing /path/to/src/node_modules/promise-polyfill/src/polyfill.js while parsing file: /path/to/src/node_modules/promise-polyfill/src/polyfill.js
[14:48:13] SyntaxError: Unexpected token (2:7) while parsing /path/to/src/node_modules/promise-polyfill/src/polyfill.js while parsing file: /path/to/src/node_modules/promise-polyfill/src/polyfill.js
    at DestroyableTransform.end [as _flush] (/path/to/src/node_modules/insert-module-globals/index.js:96:21)
    at DestroyableTransform.<anonymous> (/path/to/src/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js:115:49)
    at DestroyableTransform.g (events.js:286:16)
    at emitNone (events.js:86:13)
    at DestroyableTransform.emit (events.js:185:7)
    at prefinish (/path/to/src/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:465:12)
    at finishMaybe (/path/to/src/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:473:7)

I'm using gulp, watchify, babel :)

I'm wondering if there's a dependency version mismatch ?

Subclassing

Hey Taylor, long time no see.

What are your thoughts on changing the reference to the Promise constructor in the "then" method instead to this.constructor?

This makes it vastly easier to subclass this implementation of Promises because the Handler and handler functions are enclosed in the closure surrounding the promise.js module.

Here's what I did:

  Promise.prototype.then = function (onFulfilled, onRejected) {
    var prom = new (this.constructor)(noop);
    handle(this, new Handler(onFulfilled, onRejected, prom));
    return prom;
  };

That way, when used in practice with a class:

class PromiseTransform extends Promise {
    map() {
        let handler = data => { /* ... */ };
        this.then(handler);
    }
}

It allows you to modify the behavior of the then function while still returning a PromiseTransform as opposed to a Promise. super.then will return a Promise.

Fortunately, catch calls then, so with this change, catch will also return a PromiseTransform as opposed to a Promise. Likewise, super.catch will also return a Promise.

I'm fairly confident that if someone wants to do the same with reject or resolve they can handle those subclassed methods themselves.

I ran the tests over this and they all pass.

If you think it's worth doing, I can submit a PR.

Unexpected token: name (Promise)

I'm having an issue with gulp.

Using this as a dependency for https://github.com/github/fetch. I already updated their package.json to include v7.0.1 of this project and that made no difference.

internal/streams/legacy.js:59
      throw er; // Unhandled stream error in pipe.
      ^
Error: index.js from UglifyJs
SyntaxError: Unexpected token: name (Promise) [./~/promise-polyfill/src/polyfill.js:1,0]```

Strange additional import with webpack

Hi, when i import this module in my project (with using require('promise-polyfill') or with ProvidePlugin), after Webpack bundling i getting one additional module in my bundle - node-process polyfill for browsers. Without promise-polyfill - node-process does not exist in resulting bundle.

You have any idea why i getting this additional module?

/***/ },
/* 34 */
/***/ function(module, exports) {

// shim for using process in browser
var process = module.exports = {};

// cached from whatever global is present so that test runners that stub it
// don't break things.  But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals.  It's inside a
// function because try/catches deoptimize in certain engines.

var cachedSetTimeout;
var cachedClearTimeout;

function defaultSetTimout() {
    throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
    throw new Error('clearTimeout has not been defined');
}
(function () {
    try {
        if (typeof setTimeout === 'function') {
            cachedSetTimeout = setTimeout;
        } else {
            cachedSetTimeout = defaultSetTimout;
        }
    } catch (e) {
        cachedSetTimeout = defaultSetTimout;
    }
    try {
        if (typeof clearTimeout === 'function') {
            cachedClearTimeout = clearTimeout;
        } else {
            cachedClearTimeout = defaultClearTimeout;
        }
    } catch (e) {
        cachedClearTimeout = defaultClearTimeout;
    }
} ())
function runTimeout(fun) {
    if (cachedSetTimeout === setTimeout) {
        //normal enviroments in sane situations
        return setTimeout(fun, 0);
    }
    // if setTimeout wasn't available but was latter defined
    if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
        cachedSetTimeout = setTimeout;
        return setTimeout(fun, 0);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedSetTimeout(fun, 0);
    } catch(e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
            return cachedSetTimeout.call(null, fun, 0);
        } catch(e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
            return cachedSetTimeout.call(this, fun, 0);
        }
    }


}
function runClearTimeout(marker) {
    if (cachedClearTimeout === clearTimeout) {
        //normal enviroments in sane situations
        return clearTimeout(marker);
    }
    // if clearTimeout wasn't available but was latter defined
    if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
        cachedClearTimeout = clearTimeout;
        return clearTimeout(marker);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedClearTimeout(marker);
    } catch (e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't  trust the global object when called normally
            return cachedClearTimeout.call(null, marker);
        } catch (e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
            // Some versions of I.E. have different rules for clearTimeout vs setTimeout
            return cachedClearTimeout.call(this, marker);
        }
    }



}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;

function cleanUpNextTick() {
    if (!draining || !currentQueue) {
        return;
    }
    draining = false;
    if (currentQueue.length) {
        queue = currentQueue.concat(queue);
    } else {
        queueIndex = -1;
    }
    if (queue.length) {
        drainQueue();
    }
}

function drainQueue() {
    if (draining) {
        return;
    }
    var timeout = runTimeout(cleanUpNextTick);
    draining = true;

    var len = queue.length;
    while(len) {
        currentQueue = queue;
        queue = [];
        while (++queueIndex < len) {
            if (currentQueue) {
                currentQueue[queueIndex].run();
            }
        }
        queueIndex = -1;
        len = queue.length;
    }
    currentQueue = null;
    draining = false;
    runClearTimeout(timeout);
}

process.nextTick = function (fun) {
    var args = new Array(arguments.length - 1);
    if (arguments.length > 1) {
        for (var i = 1; i < arguments.length; i++) {
            args[i - 1] = arguments[i];
        }
    }
    queue.push(new Item(fun, args));
    if (queue.length === 1 && !draining) {
        runTimeout(drainQueue);
    }
};

// v8 likes predictible objects
function Item(fun, array) {
    this.fun = fun;
    this.array = array;
}
Item.prototype.run = function () {
    this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};

function noop() {}

process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;

process.binding = function (name) {
    throw new Error('process.binding is not supported');
};

process.cwd = function () { return '/' };
process.chdir = function (dir) {
    throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };

_unhandledRejectionFn not available on native Promise

I've been noticing a weird bug, _unhandledRejectionFn doesn't seem to fire.

My guess is : native Promise doesn't do anything with _unhandledRejectionFn, and because you do not override it when it exists and only pathc finally, this func does not fire.

A solution would be to patch/polyfill the whole Promise if the native Promise cannot handle _unhandledRejectionFn.

Or do you see another solution ?

resolve() with a promise as argument has issue

Hi, I'm trying to use this library on IE11. resolve with a promise as argument doesn't pass in argument in the .then() function. Is this a bug?

var promise = new Promise(function (resolve, reject) {
    resolve('result');
});

var promise2 = new Promise(function (resolve, reject) {
    resolve(promise);
});

promise2.then(function(result) {
    // result is undefined
});

Polyfill.js vs Promise.js

The documentation doesn't make it clear what the difference between Promise.js and Polyfill.js is. The CDN example points to Polyfill.js, while the download link points to Promise.js.

Looking at earlier issues and the changelog, I conclude that one of these overwrites the native promise object (if present) and the other only polyfills it, but this is not clear in the documentation.

Promise.all arguments is null or undefined

Hi,

I've noticed that when running the following code on browsers that supports promises and browsers that doesn't support (with this the polyfill) i get a different result:

Promise.all(null) .then(function () { console.log('then'); }) .catch(function (e) { console.log('catch', e); });

Supported browsers result:
Calling the 'catch' statement with an error of 'TypeError'.

Unsupported browsers (with the polyfill):
Throws an error on the arguments slice, doesn't call the 'catch' statement.

Is this the behavior aimed for in this polyfill?

Thanks,

Promise._immediateFn usage BUG

when handle function call Promise._immediateFn ,the parameter function should be wrapped in IIFE.

function handle(self, deferred) {
  while (self._state === 3) {
    self = self._value;
  }
  if (self._state === 0) {
    self._deferreds.push(deferred);
    return;
  }
  self._handled = true;
//----------------//
// var "self" changed when  muliti task called , the callback function should be wrapped in IIFE
//----------------//
  Promise._immediateFn(function() {
    var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
    if (cb === null) {
      (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
      return;
    }
    var ret;
    try {
      ret = cb(self._value);
    } catch (e) {
      reject(deferred.promise, e);
      return;
    }
    resolve(deferred.promise, ret);
  });
}

// Solution:

  Promise._immediateFn((function(self) {
    var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
    if (cb === null) {
      (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
      return;
    }
    var ret;
    try {
      ret = cb(self._value);
    } catch (e) {
      reject(deferred.promise, e);
      return;
    }
    resolve(deferred.promise, ret);
  })(self));

Unable to locate global object

I have included the polyfill in a universal app which is served from node and in the browser. I used the following for import into a React component ...

import 'promise-polyfill/src/polyfill';

and after webpack compile using babel I get the following error

throw new Error('unable to locate global object');

Any ideas what could be the problem?

Cheers,
Brendan

Something I don't understand about your code

I've been learning js and I'm a little confused with your resolve function, why did you deal with Promise instance separately with thenable objects? By doing so,you added a new state of "3" to the Promise,which is not quite good in my opinion.
I've checked the previous version of this,and found that you didn't deal with it as you did now.So there must be a reason.Would you be kind and tell me why?
Thanks in advance.

` function resolve(self, newValue) {

//some code
if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
var then = newValue.then;
if (newValue instanceof Promise) {
self._state = 3;
self._value = newValue;
finale(self);
return;
} else if (typeof then === 'function') {
doResolve(bind(then, newValue), self);
return;
}
}
//some code
}`

console is undefined

Hi @taylorhakes, I think it would be good if we can evaluate if console is defined before fire the console.warm in order to avoid 'console is undefined' in browser like IE8. Yes is OLD! but in same cases we need to give support.

  var onUnhandledRejection = function onUnhandledRejection(err) {
    console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console
  };

Thank you!! you made a great work!

Patch Promise.prototype.finally if non-existent?

image

Being a newer ES2018 feature, the Promise.prototype.finally is not available in many platforms (IE, Edge, Node, older version of Chrome and Firefox) yet according to MDN compatibility table...

However, https://github.com/taylorhakes/promise-polyfill/blob/master/src/polyfill.js#L19-L21 only polyfill Promise if not detected.

Should we add more logic to the polyfill?

finally.js

// Yank the function out of index.js
// I'm assuming this method is compatible with standard Promise stuffs...?

export default function (callback) {
    var constructor = this.constructor;
    return this.then(
        function (value) {
            return constructor.resolve(callback()).then(function () {
                return value;
            });
        },
        function (reason) {
            return constructor.resolve(callback()).then(function () {
                return constructor.reject(reason);
            });
        }
    );
}

index.js

import promiseFinally from './finally';
Promise.prototype['finally'] = promiseFinally;

polyfill.js

import promiseFinally from './finally';

if (!globalNS.Promise) {
  globalNS.Promise = Promise;
} else if (!globalNS.Promise.prototype['finally']) {
  globalNS.Promise.prototype['finally'] = promiseFinally;
}

Just patch the missing method, not the whole Promise if possible...

use with import

This:

import Promise from 'promise-polyfill';
window.Promise = Promise;
import 'whatwg-fetch';

Fails because imports are hoisted, and window.Promise will be undefined when whatwg-fetch gets imported.

Would you be interested in fixing this? I can submit a pull request.

What is the purpose of _setImmediateFn?

Hello,
First thank you for your great polyfill
Second I am trying to understand how this polyfill works by reading the code. I do not understand what _setImmediateFn is for. I try executing callbacks without it and thing still works. Could you help me to understand it? Thanks

Is there a issue by promise-chaining?

Hello,

I try to chain promises correct. But there is something magic.

fdescribe('Test then by promise-chaining', function () {

  function httpPromise(counter, length) {
    return new Promise(function (resolve, reject) {
      if (counter >= length) {
        resolve(counter);
      } else {
        reject(counter += 1);
      }
    });
  }

  function thenFirst() {
    return new Promise(function (resolve) {
      var length = 2;
      httpPromise(0, length)
        .then(function (counter) {
          resolve(counter);
        })
        .catch(function (counter) {
          console.log('1', counter);
          return httpPromise(counter, length)
            .catch(function (counter) {
              console.log('2', counter);
              return httpPromise(counter, length)
                .catch(function (counter) {
                  console.log('3', counter);
                  return httpPromise(counter, length);
                });
            });
        });
    });
  }

  function thenLast() {
    return new Promise(function (resolve) {
      var length = 2;
      httpPromise(0, length)
        .catch(function (counter) {
          console.log('1', counter);
          return httpPromise(counter, length)
            .catch(function (counter) {
              console.log('2', counter);
              return httpPromise(counter, length)
                .catch(function (counter) {
                  console.log('3', counter);
                  return httpPromise(counter, length);
                });
            });
        })
        .then(function (counter) {
          resolve(counter);
        });
    });
  }

  it('then first (failed)', function (done) {
    thenFirst()
      .then(function (result) {
        console.log(result);
        done();
      });
  });

  it('then last (completed)', function (done) {
    thenLast()
      .then(function (result) {
        console.log(result);
        done();
      });
  });

});
Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

prototype methods

Is there a reason why some of your methods in prototype and some not?

Polyfill Context

It would be splendid if there were some other way to set the context the polyfill applies itself to.

(function(root) {
...
})(this);

does not give much flexibility for certain build systems.

For instance, I'd love to have this ability in my start up logic:

import polyfill from 'promise-polyfill';
polyfill(window);

So that the polyfill is applied to the window context should I decide to run the polyfill into a bundling system. Otherwise, in bundling, 'this' becaomes all sorts of weird contexts.

Different behavior between Chrome/Firefox implementation and polyfill

I'm having a hard time nailing it down, but my code works in both the latest Firefox and Chrome, and when I run the tests in Selenium, but when I require the polyfill for Poltergeist/Phantomjs, I get different behavior. It appears that my callback isn't being called when I nest promises. Pardon the messy code, it's in transition:

var TimeframeStore = {
  ...
  getAll: function () {
    return new Promise(function (resolve, reject) {
      TaskStore.getAll().then(function (data) {
        this.updateModels(data);
        request({
          method: 'get',
          url: this.url(),
          success: function (data) {
            medianProductivity = data.meta.medianProductivity;
            resolve(this.getData());
          }.bind(this)
        });
      }.bind(this));
    }.bind(this));
  }
}

and inside my component:

var TimeframesIndex = React.createClass({
  ...
  componentDidMount: function () {
    TimeframeStore.getAll().then(function (data) {
      this.updateTimeframes(data);
      TimeframeStore.on('change', this.loadTasks);
    }.bind(this));
  },

  loadTasks: function () {
    TimeframeStore.getAll().then(this.updateTimeframes);
  },
  ...
}

It works as expected in componentDidMount, but when it gets called a second time in loadTasks, even though I can confirm that resolve gets called within the nested promise, updateTimeframes never gets called.

Question for converting Firefox addon to Chomium extension

I'm migrating to Chromium from Firefox but I have some addons that use promise that I'd like to convert.

Those addons like this one use promise and so they return errors like this: https://i.imgur.com/H8UYYFY.png

What would be the most easy way (since I'm not really fluent with JS) to convert them, would it be by loading the polyfill.js script from the manifest.json and adding something like that in the beginning of the .js files of the addon ??

var browser = new polyfill();

Regards :octocat:

How about publishing to CDNjs / jsDelivr

They dont have this polyfill yet, and it appers that it really works nice and doesnt provide custom property name to global object, so you neednt rewrite your code, just leave it native.

Rewrite to es6 modules

@taylorhakes Would u accept a PR with such rewrite? In current form its treated by bundlers like webpack / rollup as cjs module - thus preventing certain optimizations.

Module not found: Error: Can't resolve './finally'

I have installed this polyfill (v8.0.0) using yarn and am importing it in my typescript file like this:

import {deepSet} from './deepSet';
import {deepGet} from './deepGet';
import 'whatwg-fetch';
import Promise from 'promise-polyfill';
import merge from 'deepmerge';

But when I run npm run webpack I get following error:

ERROR in ./node_modules/promise-polyfill/src/index.js
Module not found: Error: Can't resolve './finally' in '/Users/sm/Documents/vi/biotope-configuration/node_modules/promise-polyfill/src'
 @ ./node_modules/promise-polyfill/src/index.js 1:0-39 148:31-45
 @ ./configurationLoader.ts

The module finally.js exists here:
node_modules/promise-polyfill/src/finally.js

Any idea what is wrong?

Uncaught ReferenceError: module is not defined

I'm getting Uncaught ReferenceError: module is not defined at index.js:227 when loading as
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/promise-polyfill"></script>.

Shimming setImmediate via Promise.immediateFn won't work in non-CommonJS environments

The following expression would use immediateFn, if it was defined previously on a global Promise object:

var asap = Promise.immediateFn || (typeof setImmediate === 'function' && setImmediate) ||
function(fn) { setTimeout(fn, 1); };

Thus to achieve this I'd have to do something like this in advance:

Promise = {
   immediateFn: function() { /* my shim implementation */ }
};
// or
Promise = function() {};
Promise.immediateFn = function() { /* my shim implementation */ };

But if I do this, the shim will never be installed because of this line at the end of the script:

} else if (!root.Promise) {
root.Promise = Promise;
}

I already defined Promise myself, so it won't be shimmed. Worse: If Promise was defined before by the browser, I just broke it. So perhaps checking for the necessity of shimming should be left completely to the user and the module should simply return Promise or define an AMD compatible export.

console.log does not print in promise.then in browser

Hello,
Promise.resolve(5).then(x => console.log("val:" + x))

The simple code above prints "val:5" in Chrome if we use the native Promise.
When I use the promise-polyfill it does not print!

I am using browserify, and the issue is not happening in node (it prints there)

Am i missing something simple, or what is it?

Use process.nextTick where available

Promise spec defines that promises should schedule micro tasks. In node.js this is achieved by using process.nextTick. So I would suggest that asap function first tries process.nextTick, then setImmediate (ideally, you could try MutationObserver before that), and then setTimeout.

See the following for more information: http://stackoverflow.com/a/25933985/252025

BTW, why setTimeout does not have 0 but 1 as value? This means that every time you wait for Promise to resolve you add at least 1 ms to waiting. This makes Promises as implemented by this module very slow if there is no setImmediate.

Recommended deployment approach - override browser support or not?

I see that the default behaviour of this polyfill is to override/replace the "native" browser Promise support. At least, that's how I understood the Changelog message for 2.0:

This means the library will not use built-in Promise by default. This allows for more consistency.

So clearly "consistency" is an advantage of that - are there known disadvantages? e.g. would it be slower than native Promise on some or all browsers?

I was going to instantiate like this:

if (!window.Promise) {
  window.Promise = require('promise-polyfill');

  window.Promise._unhandledRejectionFn = function(err) {
    ExceptionHandler.error(err);
  };
}

but thought I'd check here first.

Note: catching uncaught rejections and making sense of them is an important requirement for me.

global is not defined

I want to use it for browser. This is my worker code.

var promise;
if(typeof Promise === undefined) {
self.importScripts('Promise.js').Promise;
}

promise = new Promise(function (resolve, reject) {
var url = ajaxArgs.url || '',
data = ajaxArgs.data || {},
type = ajaxArgs.method || 'GET',
isGet = type === 'GET',
request = new XMLHttpRequest();
..........

Broken on any version of IE since v7.0.0

I'm requiring your project (v7.0.0) on mine along with whatwg-fetch v2.0.3 and I'm applying the polyfill myself with:

if (!window.Promise) {
  window.Promise = promisePolyfill;
  window.Promise._immediateFn = setImmediate; // this is the "setasap" package
}
require("whatwg-fetch"); // applies polyfill automatically

When I use my application on any IE browser, any fetch functions created will throw this error:

TypeError: Object doesn't support this action

Have confirmed that the exact same code does work with v6.0.2.
(version of whatwg-fetch did not change).

Rename polyfill.js to promise-polyfill.js in src and dist folders

IMO the polyfill.js is too generic a name, it's better to use promise-polyfill.js for scripts in src and dist folders to reduce the risk of namespace conflicts in projects with many dependencies. It's also less confusing as the name makes it then clear what is being polyfilled by the script.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.