es6.promise.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. 'use strict';
  2. var LIBRARY = require('./_library');
  3. var global = require('./_global');
  4. var ctx = require('./_ctx');
  5. var classof = require('./_classof');
  6. var $export = require('./_export');
  7. var isObject = require('./_is-object');
  8. var aFunction = require('./_a-function');
  9. var anInstance = require('./_an-instance');
  10. var forOf = require('./_for-of');
  11. var speciesConstructor = require('./_species-constructor');
  12. var task = require('./_task').set;
  13. var microtask = require('./_microtask')();
  14. var newPromiseCapabilityModule = require('./_new-promise-capability');
  15. var perform = require('./_perform');
  16. var promiseResolve = require('./_promise-resolve');
  17. var PROMISE = 'Promise';
  18. var TypeError = global.TypeError;
  19. var process = global.process;
  20. var $Promise = global[PROMISE];
  21. var isNode = classof(process) == 'process';
  22. var empty = function () { /* empty */ };
  23. var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper;
  24. var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f;
  25. var USE_NATIVE = !!function () {
  26. try {
  27. // correct subclassing with @@species support
  28. var promise = $Promise.resolve(1);
  29. var FakePromise = (promise.constructor = {})[require('./_wks')('species')] = function (exec) {
  30. exec(empty, empty);
  31. };
  32. // unhandled rejections tracking support, NodeJS Promise without it fails @@species test
  33. return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise;
  34. } catch (e) { /* empty */ }
  35. }();
  36. // helpers
  37. var isThenable = function (it) {
  38. var then;
  39. return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
  40. };
  41. var notify = function (promise, isReject) {
  42. if (promise._n) return;
  43. promise._n = true;
  44. var chain = promise._c;
  45. microtask(function () {
  46. var value = promise._v;
  47. var ok = promise._s == 1;
  48. var i = 0;
  49. var run = function (reaction) {
  50. var handler = ok ? reaction.ok : reaction.fail;
  51. var resolve = reaction.resolve;
  52. var reject = reaction.reject;
  53. var domain = reaction.domain;
  54. var result, then;
  55. try {
  56. if (handler) {
  57. if (!ok) {
  58. if (promise._h == 2) onHandleUnhandled(promise);
  59. promise._h = 1;
  60. }
  61. if (handler === true) result = value;
  62. else {
  63. if (domain) domain.enter();
  64. result = handler(value);
  65. if (domain) domain.exit();
  66. }
  67. if (result === reaction.promise) {
  68. reject(TypeError('Promise-chain cycle'));
  69. } else if (then = isThenable(result)) {
  70. then.call(result, resolve, reject);
  71. } else resolve(result);
  72. } else reject(value);
  73. } catch (e) {
  74. reject(e);
  75. }
  76. };
  77. while (chain.length > i) run(chain[i++]); // variable length - can't use forEach
  78. promise._c = [];
  79. promise._n = false;
  80. if (isReject && !promise._h) onUnhandled(promise);
  81. });
  82. };
  83. var onUnhandled = function (promise) {
  84. task.call(global, function () {
  85. var value = promise._v;
  86. var unhandled = isUnhandled(promise);
  87. var result, handler, console;
  88. if (unhandled) {
  89. result = perform(function () {
  90. if (isNode) {
  91. process.emit('unhandledRejection', value, promise);
  92. } else if (handler = global.onunhandledrejection) {
  93. handler({ promise: promise, reason: value });
  94. } else if ((console = global.console) && console.error) {
  95. console.error('Unhandled promise rejection', value);
  96. }
  97. });
  98. // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
  99. promise._h = isNode || isUnhandled(promise) ? 2 : 1;
  100. } promise._a = undefined;
  101. if (unhandled && result.e) throw result.v;
  102. });
  103. };
  104. var isUnhandled = function (promise) {
  105. return promise._h !== 1 && (promise._a || promise._c).length === 0;
  106. };
  107. var onHandleUnhandled = function (promise) {
  108. task.call(global, function () {
  109. var handler;
  110. if (isNode) {
  111. process.emit('rejectionHandled', promise);
  112. } else if (handler = global.onrejectionhandled) {
  113. handler({ promise: promise, reason: promise._v });
  114. }
  115. });
  116. };
  117. var $reject = function (value) {
  118. var promise = this;
  119. if (promise._d) return;
  120. promise._d = true;
  121. promise = promise._w || promise; // unwrap
  122. promise._v = value;
  123. promise._s = 2;
  124. if (!promise._a) promise._a = promise._c.slice();
  125. notify(promise, true);
  126. };
  127. var $resolve = function (value) {
  128. var promise = this;
  129. var then;
  130. if (promise._d) return;
  131. promise._d = true;
  132. promise = promise._w || promise; // unwrap
  133. try {
  134. if (promise === value) throw TypeError("Promise can't be resolved itself");
  135. if (then = isThenable(value)) {
  136. microtask(function () {
  137. var wrapper = { _w: promise, _d: false }; // wrap
  138. try {
  139. then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
  140. } catch (e) {
  141. $reject.call(wrapper, e);
  142. }
  143. });
  144. } else {
  145. promise._v = value;
  146. promise._s = 1;
  147. notify(promise, false);
  148. }
  149. } catch (e) {
  150. $reject.call({ _w: promise, _d: false }, e); // wrap
  151. }
  152. };
  153. // constructor polyfill
  154. if (!USE_NATIVE) {
  155. // 25.4.3.1 Promise(executor)
  156. $Promise = function Promise(executor) {
  157. anInstance(this, $Promise, PROMISE, '_h');
  158. aFunction(executor);
  159. Internal.call(this);
  160. try {
  161. executor(ctx($resolve, this, 1), ctx($reject, this, 1));
  162. } catch (err) {
  163. $reject.call(this, err);
  164. }
  165. };
  166. // eslint-disable-next-line no-unused-vars
  167. Internal = function Promise(executor) {
  168. this._c = []; // <- awaiting reactions
  169. this._a = undefined; // <- checked in isUnhandled reactions
  170. this._s = 0; // <- state
  171. this._d = false; // <- done
  172. this._v = undefined; // <- value
  173. this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled
  174. this._n = false; // <- notify
  175. };
  176. Internal.prototype = require('./_redefine-all')($Promise.prototype, {
  177. // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
  178. then: function then(onFulfilled, onRejected) {
  179. var reaction = newPromiseCapability(speciesConstructor(this, $Promise));
  180. reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
  181. reaction.fail = typeof onRejected == 'function' && onRejected;
  182. reaction.domain = isNode ? process.domain : undefined;
  183. this._c.push(reaction);
  184. if (this._a) this._a.push(reaction);
  185. if (this._s) notify(this, false);
  186. return reaction.promise;
  187. },
  188. // 25.4.5.1 Promise.prototype.catch(onRejected)
  189. 'catch': function (onRejected) {
  190. return this.then(undefined, onRejected);
  191. }
  192. });
  193. OwnPromiseCapability = function () {
  194. var promise = new Internal();
  195. this.promise = promise;
  196. this.resolve = ctx($resolve, promise, 1);
  197. this.reject = ctx($reject, promise, 1);
  198. };
  199. newPromiseCapabilityModule.f = newPromiseCapability = function (C) {
  200. return C === $Promise || C === Wrapper
  201. ? new OwnPromiseCapability(C)
  202. : newGenericPromiseCapability(C);
  203. };
  204. }
  205. $export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise });
  206. require('./_set-to-string-tag')($Promise, PROMISE);
  207. require('./_set-species')(PROMISE);
  208. Wrapper = require('./_core')[PROMISE];
  209. // statics
  210. $export($export.S + $export.F * !USE_NATIVE, PROMISE, {
  211. // 25.4.4.5 Promise.reject(r)
  212. reject: function reject(r) {
  213. var capability = newPromiseCapability(this);
  214. var $$reject = capability.reject;
  215. $$reject(r);
  216. return capability.promise;
  217. }
  218. });
  219. $export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, {
  220. // 25.4.4.6 Promise.resolve(x)
  221. resolve: function resolve(x) {
  222. return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x);
  223. }
  224. });
  225. $export($export.S + $export.F * !(USE_NATIVE && require('./_iter-detect')(function (iter) {
  226. $Promise.all(iter)['catch'](empty);
  227. })), PROMISE, {
  228. // 25.4.4.1 Promise.all(iterable)
  229. all: function all(iterable) {
  230. var C = this;
  231. var capability = newPromiseCapability(C);
  232. var resolve = capability.resolve;
  233. var reject = capability.reject;
  234. var result = perform(function () {
  235. var values = [];
  236. var index = 0;
  237. var remaining = 1;
  238. forOf(iterable, false, function (promise) {
  239. var $index = index++;
  240. var alreadyCalled = false;
  241. values.push(undefined);
  242. remaining++;
  243. C.resolve(promise).then(function (value) {
  244. if (alreadyCalled) return;
  245. alreadyCalled = true;
  246. values[$index] = value;
  247. --remaining || resolve(values);
  248. }, reject);
  249. });
  250. --remaining || resolve(values);
  251. });
  252. if (result.e) reject(result.v);
  253. return capability.promise;
  254. },
  255. // 25.4.4.4 Promise.race(iterable)
  256. race: function race(iterable) {
  257. var C = this;
  258. var capability = newPromiseCapability(C);
  259. var reject = capability.reject;
  260. var result = perform(function () {
  261. forOf(iterable, false, function (promise) {
  262. C.resolve(promise).then(capability.resolve, reject);
  263. });
  264. });
  265. if (result.e) reject(result.v);
  266. return capability.promise;
  267. }
  268. });