es.promise.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. 'use strict';
  2. var $ = require('../internals/export');
  3. var IS_PURE = require('../internals/is-pure');
  4. var global = require('../internals/global');
  5. var getBuiltIn = require('../internals/get-built-in');
  6. var NativePromise = require('../internals/native-promise-constructor');
  7. var redefine = require('../internals/redefine');
  8. var redefineAll = require('../internals/redefine-all');
  9. var setPrototypeOf = require('../internals/object-set-prototype-of');
  10. var setToStringTag = require('../internals/set-to-string-tag');
  11. var setSpecies = require('../internals/set-species');
  12. var isObject = require('../internals/is-object');
  13. var aFunction = require('../internals/a-function');
  14. var anInstance = require('../internals/an-instance');
  15. var inspectSource = require('../internals/inspect-source');
  16. var iterate = require('../internals/iterate');
  17. var checkCorrectnessOfIteration = require('../internals/check-correctness-of-iteration');
  18. var speciesConstructor = require('../internals/species-constructor');
  19. var task = require('../internals/task').set;
  20. var microtask = require('../internals/microtask');
  21. var promiseResolve = require('../internals/promise-resolve');
  22. var hostReportErrors = require('../internals/host-report-errors');
  23. var newPromiseCapabilityModule = require('../internals/new-promise-capability');
  24. var perform = require('../internals/perform');
  25. var InternalStateModule = require('../internals/internal-state');
  26. var isForced = require('../internals/is-forced');
  27. var wellKnownSymbol = require('../internals/well-known-symbol');
  28. var IS_BROWSER = require('../internals/engine-is-browser');
  29. var IS_NODE = require('../internals/engine-is-node');
  30. var V8_VERSION = require('../internals/engine-v8-version');
  31. var SPECIES = wellKnownSymbol('species');
  32. var PROMISE = 'Promise';
  33. var getInternalState = InternalStateModule.get;
  34. var setInternalState = InternalStateModule.set;
  35. var getInternalPromiseState = InternalStateModule.getterFor(PROMISE);
  36. var NativePromisePrototype = NativePromise && NativePromise.prototype;
  37. var PromiseConstructor = NativePromise;
  38. var PromiseConstructorPrototype = NativePromisePrototype;
  39. var TypeError = global.TypeError;
  40. var document = global.document;
  41. var process = global.process;
  42. var newPromiseCapability = newPromiseCapabilityModule.f;
  43. var newGenericPromiseCapability = newPromiseCapability;
  44. var DISPATCH_EVENT = !!(document && document.createEvent && global.dispatchEvent);
  45. var NATIVE_REJECTION_EVENT = typeof PromiseRejectionEvent == 'function';
  46. var UNHANDLED_REJECTION = 'unhandledrejection';
  47. var REJECTION_HANDLED = 'rejectionhandled';
  48. var PENDING = 0;
  49. var FULFILLED = 1;
  50. var REJECTED = 2;
  51. var HANDLED = 1;
  52. var UNHANDLED = 2;
  53. var SUBCLASSING = false;
  54. var Internal, OwnPromiseCapability, PromiseWrapper, nativeThen;
  55. var FORCED = isForced(PROMISE, function () {
  56. var GLOBAL_CORE_JS_PROMISE = inspectSource(PromiseConstructor) !== String(PromiseConstructor);
  57. // V8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables
  58. // https://bugs.chromium.org/p/chromium/issues/detail?id=830565
  59. // We can't detect it synchronously, so just check versions
  60. if (!GLOBAL_CORE_JS_PROMISE && V8_VERSION === 66) return true;
  61. // We need Promise#finally in the pure version for preventing prototype pollution
  62. if (IS_PURE && !PromiseConstructorPrototype['finally']) return true;
  63. // We can't use @@species feature detection in V8 since it causes
  64. // deoptimization and performance degradation
  65. // https://github.com/zloirock/core-js/issues/679
  66. if (V8_VERSION >= 51 && /native code/.test(PromiseConstructor)) return false;
  67. // Detect correctness of subclassing with @@species support
  68. var promise = new PromiseConstructor(function (resolve) { resolve(1); });
  69. var FakePromise = function (exec) {
  70. exec(function () { /* empty */ }, function () { /* empty */ });
  71. };
  72. var constructor = promise.constructor = {};
  73. constructor[SPECIES] = FakePromise;
  74. SUBCLASSING = promise.then(function () { /* empty */ }) instanceof FakePromise;
  75. if (!SUBCLASSING) return true;
  76. // Unhandled rejections tracking support, NodeJS Promise without it fails @@species test
  77. return !GLOBAL_CORE_JS_PROMISE && IS_BROWSER && !NATIVE_REJECTION_EVENT;
  78. });
  79. var INCORRECT_ITERATION = FORCED || !checkCorrectnessOfIteration(function (iterable) {
  80. PromiseConstructor.all(iterable)['catch'](function () { /* empty */ });
  81. });
  82. // helpers
  83. var isThenable = function (it) {
  84. var then;
  85. return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
  86. };
  87. var notify = function (state, isReject) {
  88. if (state.notified) return;
  89. state.notified = true;
  90. var chain = state.reactions;
  91. microtask(function () {
  92. var value = state.value;
  93. var ok = state.state == FULFILLED;
  94. var index = 0;
  95. // variable length - can't use forEach
  96. while (chain.length > index) {
  97. var reaction = chain[index++];
  98. var handler = ok ? reaction.ok : reaction.fail;
  99. var resolve = reaction.resolve;
  100. var reject = reaction.reject;
  101. var domain = reaction.domain;
  102. var result, then, exited;
  103. try {
  104. if (handler) {
  105. if (!ok) {
  106. if (state.rejection === UNHANDLED) onHandleUnhandled(state);
  107. state.rejection = HANDLED;
  108. }
  109. if (handler === true) result = value;
  110. else {
  111. if (domain) domain.enter();
  112. result = handler(value); // can throw
  113. if (domain) {
  114. domain.exit();
  115. exited = true;
  116. }
  117. }
  118. if (result === reaction.promise) {
  119. reject(TypeError('Promise-chain cycle'));
  120. } else if (then = isThenable(result)) {
  121. then.call(result, resolve, reject);
  122. } else resolve(result);
  123. } else reject(value);
  124. } catch (error) {
  125. if (domain && !exited) domain.exit();
  126. reject(error);
  127. }
  128. }
  129. state.reactions = [];
  130. state.notified = false;
  131. if (isReject && !state.rejection) onUnhandled(state);
  132. });
  133. };
  134. var dispatchEvent = function (name, promise, reason) {
  135. var event, handler;
  136. if (DISPATCH_EVENT) {
  137. event = document.createEvent('Event');
  138. event.promise = promise;
  139. event.reason = reason;
  140. event.initEvent(name, false, true);
  141. global.dispatchEvent(event);
  142. } else event = { promise: promise, reason: reason };
  143. if (!NATIVE_REJECTION_EVENT && (handler = global['on' + name])) handler(event);
  144. else if (name === UNHANDLED_REJECTION) hostReportErrors('Unhandled promise rejection', reason);
  145. };
  146. var onUnhandled = function (state) {
  147. task.call(global, function () {
  148. var promise = state.facade;
  149. var value = state.value;
  150. var IS_UNHANDLED = isUnhandled(state);
  151. var result;
  152. if (IS_UNHANDLED) {
  153. result = perform(function () {
  154. if (IS_NODE) {
  155. process.emit('unhandledRejection', value, promise);
  156. } else dispatchEvent(UNHANDLED_REJECTION, promise, value);
  157. });
  158. // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
  159. state.rejection = IS_NODE || isUnhandled(state) ? UNHANDLED : HANDLED;
  160. if (result.error) throw result.value;
  161. }
  162. });
  163. };
  164. var isUnhandled = function (state) {
  165. return state.rejection !== HANDLED && !state.parent;
  166. };
  167. var onHandleUnhandled = function (state) {
  168. task.call(global, function () {
  169. var promise = state.facade;
  170. if (IS_NODE) {
  171. process.emit('rejectionHandled', promise);
  172. } else dispatchEvent(REJECTION_HANDLED, promise, state.value);
  173. });
  174. };
  175. var bind = function (fn, state, unwrap) {
  176. return function (value) {
  177. fn(state, value, unwrap);
  178. };
  179. };
  180. var internalReject = function (state, value, unwrap) {
  181. if (state.done) return;
  182. state.done = true;
  183. if (unwrap) state = unwrap;
  184. state.value = value;
  185. state.state = REJECTED;
  186. notify(state, true);
  187. };
  188. var internalResolve = function (state, value, unwrap) {
  189. if (state.done) return;
  190. state.done = true;
  191. if (unwrap) state = unwrap;
  192. try {
  193. if (state.facade === value) throw TypeError("Promise can't be resolved itself");
  194. var then = isThenable(value);
  195. if (then) {
  196. microtask(function () {
  197. var wrapper = { done: false };
  198. try {
  199. then.call(value,
  200. bind(internalResolve, wrapper, state),
  201. bind(internalReject, wrapper, state)
  202. );
  203. } catch (error) {
  204. internalReject(wrapper, error, state);
  205. }
  206. });
  207. } else {
  208. state.value = value;
  209. state.state = FULFILLED;
  210. notify(state, false);
  211. }
  212. } catch (error) {
  213. internalReject({ done: false }, error, state);
  214. }
  215. };
  216. // constructor polyfill
  217. if (FORCED) {
  218. // 25.4.3.1 Promise(executor)
  219. PromiseConstructor = function Promise(executor) {
  220. anInstance(this, PromiseConstructor, PROMISE);
  221. aFunction(executor);
  222. Internal.call(this);
  223. var state = getInternalState(this);
  224. try {
  225. executor(bind(internalResolve, state), bind(internalReject, state));
  226. } catch (error) {
  227. internalReject(state, error);
  228. }
  229. };
  230. PromiseConstructorPrototype = PromiseConstructor.prototype;
  231. // eslint-disable-next-line no-unused-vars -- required for `.length`
  232. Internal = function Promise(executor) {
  233. setInternalState(this, {
  234. type: PROMISE,
  235. done: false,
  236. notified: false,
  237. parent: false,
  238. reactions: [],
  239. rejection: false,
  240. state: PENDING,
  241. value: undefined
  242. });
  243. };
  244. Internal.prototype = redefineAll(PromiseConstructorPrototype, {
  245. // `Promise.prototype.then` method
  246. // https://tc39.es/ecma262/#sec-promise.prototype.then
  247. then: function then(onFulfilled, onRejected) {
  248. var state = getInternalPromiseState(this);
  249. var reaction = newPromiseCapability(speciesConstructor(this, PromiseConstructor));
  250. reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
  251. reaction.fail = typeof onRejected == 'function' && onRejected;
  252. reaction.domain = IS_NODE ? process.domain : undefined;
  253. state.parent = true;
  254. state.reactions.push(reaction);
  255. if (state.state != PENDING) notify(state, false);
  256. return reaction.promise;
  257. },
  258. // `Promise.prototype.catch` method
  259. // https://tc39.es/ecma262/#sec-promise.prototype.catch
  260. 'catch': function (onRejected) {
  261. return this.then(undefined, onRejected);
  262. }
  263. });
  264. OwnPromiseCapability = function () {
  265. var promise = new Internal();
  266. var state = getInternalState(promise);
  267. this.promise = promise;
  268. this.resolve = bind(internalResolve, state);
  269. this.reject = bind(internalReject, state);
  270. };
  271. newPromiseCapabilityModule.f = newPromiseCapability = function (C) {
  272. return C === PromiseConstructor || C === PromiseWrapper
  273. ? new OwnPromiseCapability(C)
  274. : newGenericPromiseCapability(C);
  275. };
  276. if (!IS_PURE && typeof NativePromise == 'function' && NativePromisePrototype !== Object.prototype) {
  277. nativeThen = NativePromisePrototype.then;
  278. if (!SUBCLASSING) {
  279. // make `Promise#then` return a polyfilled `Promise` for native promise-based APIs
  280. redefine(NativePromisePrototype, 'then', function then(onFulfilled, onRejected) {
  281. var that = this;
  282. return new PromiseConstructor(function (resolve, reject) {
  283. nativeThen.call(that, resolve, reject);
  284. }).then(onFulfilled, onRejected);
  285. // https://github.com/zloirock/core-js/issues/640
  286. }, { unsafe: true });
  287. // makes sure that native promise-based APIs `Promise#catch` properly works with patched `Promise#then`
  288. redefine(NativePromisePrototype, 'catch', PromiseConstructorPrototype['catch'], { unsafe: true });
  289. }
  290. // make `.constructor === Promise` work for native promise-based APIs
  291. try {
  292. delete NativePromisePrototype.constructor;
  293. } catch (error) { /* empty */ }
  294. // make `instanceof Promise` work for native promise-based APIs
  295. if (setPrototypeOf) {
  296. setPrototypeOf(NativePromisePrototype, PromiseConstructorPrototype);
  297. }
  298. }
  299. }
  300. $({ global: true, wrap: true, forced: FORCED }, {
  301. Promise: PromiseConstructor
  302. });
  303. setToStringTag(PromiseConstructor, PROMISE, false, true);
  304. setSpecies(PROMISE);
  305. PromiseWrapper = getBuiltIn(PROMISE);
  306. // statics
  307. $({ target: PROMISE, stat: true, forced: FORCED }, {
  308. // `Promise.reject` method
  309. // https://tc39.es/ecma262/#sec-promise.reject
  310. reject: function reject(r) {
  311. var capability = newPromiseCapability(this);
  312. capability.reject.call(undefined, r);
  313. return capability.promise;
  314. }
  315. });
  316. $({ target: PROMISE, stat: true, forced: IS_PURE || FORCED }, {
  317. // `Promise.resolve` method
  318. // https://tc39.es/ecma262/#sec-promise.resolve
  319. resolve: function resolve(x) {
  320. return promiseResolve(IS_PURE && this === PromiseWrapper ? PromiseConstructor : this, x);
  321. }
  322. });
  323. $({ target: PROMISE, stat: true, forced: INCORRECT_ITERATION }, {
  324. // `Promise.all` method
  325. // https://tc39.es/ecma262/#sec-promise.all
  326. all: function all(iterable) {
  327. var C = this;
  328. var capability = newPromiseCapability(C);
  329. var resolve = capability.resolve;
  330. var reject = capability.reject;
  331. var result = perform(function () {
  332. var $promiseResolve = aFunction(C.resolve);
  333. var values = [];
  334. var counter = 0;
  335. var remaining = 1;
  336. iterate(iterable, function (promise) {
  337. var index = counter++;
  338. var alreadyCalled = false;
  339. values.push(undefined);
  340. remaining++;
  341. $promiseResolve.call(C, promise).then(function (value) {
  342. if (alreadyCalled) return;
  343. alreadyCalled = true;
  344. values[index] = value;
  345. --remaining || resolve(values);
  346. }, reject);
  347. });
  348. --remaining || resolve(values);
  349. });
  350. if (result.error) reject(result.value);
  351. return capability.promise;
  352. },
  353. // `Promise.race` method
  354. // https://tc39.es/ecma262/#sec-promise.race
  355. race: function race(iterable) {
  356. var C = this;
  357. var capability = newPromiseCapability(C);
  358. var reject = capability.reject;
  359. var result = perform(function () {
  360. var $promiseResolve = aFunction(C.resolve);
  361. iterate(iterable, function (promise) {
  362. $promiseResolve.call(C, promise).then(capability.resolve, reject);
  363. });
  364. });
  365. if (result.error) reject(result.value);
  366. return capability.promise;
  367. }
  368. });