Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 

287 righe
6.8 KiB

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