promise.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. /* Copyright (c) 2014 Taylor Hakes
  2. * Copyright (c) 2014 Forbes Lindesay
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. (function (root) {
  23. // Store setTimeout reference so promise-polyfill will be unaffected by
  24. // other code modifying setTimeout (like sinon.useFakeTimers())
  25. var setTimeoutFunc = setTimeout;
  26. function noop() {}
  27. // Polyfill for Function.prototype.bind
  28. function bind(fn, thisArg) {
  29. return function () {
  30. fn.apply(thisArg, arguments);
  31. };
  32. }
  33. function Promise(fn) {
  34. if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new');
  35. if (typeof fn !== 'function') throw new TypeError('not a function');
  36. this._state = 0;
  37. this._handled = false;
  38. this._value = undefined;
  39. this._deferreds = [];
  40. doResolve(fn, this);
  41. }
  42. function handle(self, deferred) {
  43. while (self._state === 3) {
  44. self = self._value;
  45. }
  46. if (self._state === 0) {
  47. self._deferreds.push(deferred);
  48. return;
  49. }
  50. self._handled = true;
  51. Promise._immediateFn(function () {
  52. var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
  53. if (cb === null) {
  54. (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
  55. return;
  56. }
  57. var ret;
  58. try {
  59. ret = cb(self._value);
  60. } catch (e) {
  61. reject(deferred.promise, e);
  62. return;
  63. }
  64. resolve(deferred.promise, ret);
  65. });
  66. }
  67. function resolve(self, newValue) {
  68. try {
  69. // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
  70. if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.');
  71. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  72. var then = newValue.then;
  73. if (newValue instanceof Promise) {
  74. self._state = 3;
  75. self._value = newValue;
  76. finale(self);
  77. return;
  78. } else if (typeof then === 'function') {
  79. doResolve(bind(then, newValue), self);
  80. return;
  81. }
  82. }
  83. self._state = 1;
  84. self._value = newValue;
  85. finale(self);
  86. } catch (e) {
  87. reject(self, e);
  88. }
  89. }
  90. function reject(self, newValue) {
  91. self._state = 2;
  92. self._value = newValue;
  93. finale(self);
  94. }
  95. function finale(self) {
  96. if (self._state === 2 && self._deferreds.length === 0) {
  97. Promise._immediateFn(function() {
  98. if (!self._handled) {
  99. Promise._unhandledRejectionFn(self._value);
  100. }
  101. });
  102. }
  103. for (var i = 0, len = self._deferreds.length; i < len; i++) {
  104. handle(self, self._deferreds[i]);
  105. }
  106. self._deferreds = null;
  107. }
  108. function Handler(onFulfilled, onRejected, promise) {
  109. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  110. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  111. this.promise = promise;
  112. }
  113. /**
  114. * Take a potentially misbehaving resolver function and make sure
  115. * onFulfilled and onRejected are only called once.
  116. *
  117. * Makes no guarantees about asynchrony.
  118. */
  119. function doResolve(fn, self) {
  120. var done = false;
  121. try {
  122. fn(function (value) {
  123. if (done) return;
  124. done = true;
  125. resolve(self, value);
  126. }, function (reason) {
  127. if (done) return;
  128. done = true;
  129. reject(self, reason);
  130. });
  131. } catch (ex) {
  132. if (done) return;
  133. done = true;
  134. reject(self, ex);
  135. }
  136. }
  137. Promise.prototype['catch'] = function (onRejected) {
  138. return this.then(null, onRejected);
  139. };
  140. Promise.prototype.then = function (onFulfilled, onRejected) {
  141. var prom = new (this.constructor)(noop);
  142. handle(this, new Handler(onFulfilled, onRejected, prom));
  143. return prom;
  144. };
  145. Promise.all = function (arr) {
  146. var args = Array.prototype.slice.call(arr);
  147. return new Promise(function (resolve, reject) {
  148. if (args.length === 0) return resolve([]);
  149. var remaining = args.length;
  150. function res(i, val) {
  151. try {
  152. if (val && (typeof val === 'object' || typeof val === 'function')) {
  153. var then = val.then;
  154. if (typeof then === 'function') {
  155. then.call(val, function (val) {
  156. res(i, val);
  157. }, reject);
  158. return;
  159. }
  160. }
  161. args[i] = val;
  162. if (--remaining === 0) {
  163. resolve(args);
  164. }
  165. } catch (ex) {
  166. reject(ex);
  167. }
  168. }
  169. for (var i = 0; i < args.length; i++) {
  170. res(i, args[i]);
  171. }
  172. });
  173. };
  174. Promise.resolve = function (value) {
  175. if (value && typeof value === 'object' && value.constructor === Promise) {
  176. return value;
  177. }
  178. return new Promise(function (resolve) {
  179. resolve(value);
  180. });
  181. };
  182. Promise.reject = function (value) {
  183. return new Promise(function (resolve, reject) {
  184. reject(value);
  185. });
  186. };
  187. Promise.race = function (values) {
  188. return new Promise(function (resolve, reject) {
  189. for (var i = 0, len = values.length; i < len; i++) {
  190. values[i].then(resolve, reject);
  191. }
  192. });
  193. };
  194. // Use polyfill for setImmediate for performance gains
  195. Promise._immediateFn = (typeof setImmediate === 'function' && function (fn) { setImmediate(fn); }) ||
  196. function (fn) {
  197. setTimeoutFunc(fn, 0);
  198. };
  199. Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  200. if (typeof console !== 'undefined' && console) {
  201. console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console
  202. }
  203. };
  204. /**
  205. * Set the immediate function to execute callbacks
  206. * @param fn {function} Function to execute
  207. * @deprecated
  208. */
  209. Promise._setImmediateFn = function _setImmediateFn(fn) {
  210. Promise._immediateFn = fn;
  211. };
  212. /**
  213. * Change the function to execute on unhandled rejection
  214. * @param {function} fn Function to execute on unhandled rejection
  215. * @deprecated
  216. */
  217. Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {
  218. Promise._unhandledRejectionFn = fn;
  219. };
  220. if (typeof module !== 'undefined' && module.exports) {
  221. module.exports = Promise;
  222. } else if (!root.Promise) {
  223. root.Promise = Promise;
  224. }
  225. })(this);