promise-constructor-detection.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. var global = require('../internals/global');
  2. var NativePromiseConstructor = require('../internals/promise-native-constructor');
  3. var isCallable = require('../internals/is-callable');
  4. var isForced = require('../internals/is-forced');
  5. var inspectSource = require('../internals/inspect-source');
  6. var wellKnownSymbol = require('../internals/well-known-symbol');
  7. var IS_BROWSER = require('../internals/engine-is-browser');
  8. var IS_PURE = require('../internals/is-pure');
  9. var V8_VERSION = require('../internals/engine-v8-version');
  10. var NativePromisePrototype = NativePromiseConstructor && NativePromiseConstructor.prototype;
  11. var SPECIES = wellKnownSymbol('species');
  12. var SUBCLASSING = false;
  13. var NATIVE_PROMISE_REJECTION_EVENT = isCallable(global.PromiseRejectionEvent);
  14. var FORCED_PROMISE_CONSTRUCTOR = isForced('Promise', function () {
  15. var PROMISE_CONSTRUCTOR_SOURCE = inspectSource(NativePromiseConstructor);
  16. var GLOBAL_CORE_JS_PROMISE = PROMISE_CONSTRUCTOR_SOURCE !== String(NativePromiseConstructor);
  17. // V8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables
  18. // https://bugs.chromium.org/p/chromium/issues/detail?id=830565
  19. // We can't detect it synchronously, so just check versions
  20. if (!GLOBAL_CORE_JS_PROMISE && V8_VERSION === 66) return true;
  21. // We need Promise#{ catch, finally } in the pure version for preventing prototype pollution
  22. if (IS_PURE && !(NativePromisePrototype['catch'] && NativePromisePrototype['finally'])) return true;
  23. // We can't use @@species feature detection in V8 since it causes
  24. // deoptimization and performance degradation
  25. // https://github.com/zloirock/core-js/issues/679
  26. if (V8_VERSION >= 51 && /native code/.test(PROMISE_CONSTRUCTOR_SOURCE)) return false;
  27. // Detect correctness of subclassing with @@species support
  28. var promise = new NativePromiseConstructor(function (resolve) { resolve(1); });
  29. var FakePromise = function (exec) {
  30. exec(function () { /* empty */ }, function () { /* empty */ });
  31. };
  32. var constructor = promise.constructor = {};
  33. constructor[SPECIES] = FakePromise;
  34. SUBCLASSING = promise.then(function () { /* empty */ }) instanceof FakePromise;
  35. if (!SUBCLASSING) return true;
  36. // Unhandled rejections tracking support, NodeJS Promise without it fails @@species test
  37. return !GLOBAL_CORE_JS_PROMISE && IS_BROWSER && !NATIVE_PROMISE_REJECTION_EVENT;
  38. });
  39. module.exports = {
  40. CONSTRUCTOR: FORCED_PROMISE_CONSTRUCTOR,
  41. REJECTION_EVENT: NATIVE_PROMISE_REJECTION_EVENT,
  42. SUBCLASSING: SUBCLASSING
  43. };