promise.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  3. typeof define === 'function' && define.amd ? define(factory) :
  4. (global.Promise = factory());
  5. }(this, (function () { 'use strict';
  6. // Store setTimeout reference so promise-polyfill will be unaffected by
  7. // other code modifying setTimeout (like sinon.useFakeTimers())
  8. var setTimeoutFunc = setTimeout;
  9. function noop() {}
  10. // Polyfill for Function.prototype.bind
  11. function bind(fn, thisArg) {
  12. return function() {
  13. fn.apply(thisArg, arguments);
  14. };
  15. }
  16. function Promise(fn) {
  17. if (!(this instanceof Promise))
  18. throw new TypeError('Promises must be constructed via new');
  19. if (typeof fn !== 'function') throw new TypeError('not a function');
  20. this._state = 0;
  21. this._handled = false;
  22. this._value = undefined;
  23. this._deferreds = [];
  24. doResolve(fn, this);
  25. }
  26. function handle(self, deferred) {
  27. while (self._state === 3) {
  28. self = self._value;
  29. }
  30. if (self._state === 0) {
  31. self._deferreds.push(deferred);
  32. return;
  33. }
  34. self._handled = true;
  35. Promise._immediateFn(function() {
  36. var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
  37. if (cb === null) {
  38. (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
  39. return;
  40. }
  41. var ret;
  42. try {
  43. ret = cb(self._value);
  44. } catch (e) {
  45. reject(deferred.promise, e);
  46. return;
  47. }
  48. resolve(deferred.promise, ret);
  49. });
  50. }
  51. function resolve(self, newValue) {
  52. try {
  53. // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
  54. if (newValue === self)
  55. throw new TypeError('A promise cannot be resolved with itself.');
  56. if (
  57. newValue &&
  58. (typeof newValue === 'object' || typeof newValue === 'function')
  59. ) {
  60. var then = newValue.then;
  61. if (newValue instanceof Promise) {
  62. self._state = 3;
  63. self._value = newValue;
  64. finale(self);
  65. return;
  66. } else if (typeof then === 'function') {
  67. doResolve(bind(then, newValue), self);
  68. return;
  69. }
  70. }
  71. self._state = 1;
  72. self._value = newValue;
  73. finale(self);
  74. } catch (e) {
  75. reject(self, e);
  76. }
  77. }
  78. function reject(self, newValue) {
  79. self._state = 2;
  80. self._value = newValue;
  81. finale(self);
  82. }
  83. function finale(self) {
  84. if (self._state === 2 && self._deferreds.length === 0) {
  85. Promise._immediateFn(function() {
  86. if (!self._handled) {
  87. Promise._unhandledRejectionFn(self._value);
  88. }
  89. });
  90. }
  91. for (var i = 0, len = self._deferreds.length; i < len; i++) {
  92. handle(self, self._deferreds[i]);
  93. }
  94. self._deferreds = null;
  95. }
  96. function Handler(onFulfilled, onRejected, promise) {
  97. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  98. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  99. this.promise = promise;
  100. }
  101. /**
  102. * Take a potentially misbehaving resolver function and make sure
  103. * onFulfilled and onRejected are only called once.
  104. *
  105. * Makes no guarantees about asynchrony.
  106. */
  107. function doResolve(fn, self) {
  108. var done = false;
  109. try {
  110. fn(
  111. function(value) {
  112. if (done) return;
  113. done = true;
  114. resolve(self, value);
  115. },
  116. function(reason) {
  117. if (done) return;
  118. done = true;
  119. reject(self, reason);
  120. }
  121. );
  122. } catch (ex) {
  123. if (done) return;
  124. done = true;
  125. reject(self, ex);
  126. }
  127. }
  128. Promise.prototype['catch'] = function(onRejected) {
  129. return this.then(null, onRejected);
  130. };
  131. Promise.prototype.then = function(onFulfilled, onRejected) {
  132. var prom = new this.constructor(noop);
  133. handle(this, new Handler(onFulfilled, onRejected, prom));
  134. return prom;
  135. };
  136. Promise.prototype['finally'] = function(callback) {
  137. var constructor = this.constructor;
  138. return this.then(
  139. function(value) {
  140. return constructor.resolve(callback()).then(function() {
  141. return value;
  142. });
  143. },
  144. function(reason) {
  145. return constructor.resolve(callback()).then(function() {
  146. return constructor.reject(reason);
  147. });
  148. }
  149. );
  150. };
  151. Promise.all = function(arr) {
  152. return new Promise(function(resolve, reject) {
  153. if (!arr || typeof arr.length === 'undefined')
  154. throw new TypeError('Promise.all accepts an array');
  155. var args = Array.prototype.slice.call(arr);
  156. if (args.length === 0) return resolve([]);
  157. var remaining = args.length;
  158. function res(i, val) {
  159. try {
  160. if (val && (typeof val === 'object' || typeof val === 'function')) {
  161. var then = val.then;
  162. if (typeof then === 'function') {
  163. then.call(
  164. val,
  165. function(val) {
  166. res(i, val);
  167. },
  168. reject
  169. );
  170. return;
  171. }
  172. }
  173. args[i] = val;
  174. if (--remaining === 0) {
  175. resolve(args);
  176. }
  177. } catch (ex) {
  178. reject(ex);
  179. }
  180. }
  181. for (var i = 0; i < args.length; i++) {
  182. res(i, args[i]);
  183. }
  184. });
  185. };
  186. Promise.resolve = function(value) {
  187. if (value && typeof value === 'object' && value.constructor === Promise) {
  188. return value;
  189. }
  190. return new Promise(function(resolve) {
  191. resolve(value);
  192. });
  193. };
  194. Promise.reject = function(value) {
  195. return new Promise(function(resolve, reject) {
  196. reject(value);
  197. });
  198. };
  199. Promise.race = function(values) {
  200. return new Promise(function(resolve, reject) {
  201. for (var i = 0, len = values.length; i < len; i++) {
  202. values[i].then(resolve, reject);
  203. }
  204. });
  205. };
  206. // Use polyfill for setImmediate for performance gains
  207. Promise._immediateFn =
  208. (typeof setImmediate === 'function' &&
  209. function(fn) {
  210. setImmediate(fn);
  211. }) ||
  212. function(fn) {
  213. setTimeoutFunc(fn, 0);
  214. };
  215. Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  216. if (typeof console !== 'undefined' && console) {
  217. console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console
  218. }
  219. };
  220. return Promise;
  221. })));