es6.promise.js 10 KB

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