es.promise.js 13 KB

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