polyfill.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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. // @ts-ignore
  14. return constructor.resolve(callback()).then(function() {
  15. return value;
  16. });
  17. },
  18. function(reason) {
  19. // @ts-ignore
  20. return constructor.resolve(callback()).then(function() {
  21. // @ts-ignore
  22. return constructor.reject(reason);
  23. });
  24. }
  25. );
  26. }
  27. function allSettled(arr) {
  28. var P = this;
  29. return new P(function(resolve, reject) {
  30. if (!(arr && typeof arr.length !== 'undefined')) {
  31. return reject(
  32. new TypeError(
  33. typeof arr +
  34. ' ' +
  35. arr +
  36. ' is not iterable(cannot read property Symbol(Symbol.iterator))'
  37. )
  38. );
  39. }
  40. var args = Array.prototype.slice.call(arr);
  41. if (args.length === 0) return resolve([]);
  42. var remaining = args.length;
  43. function res(i, val) {
  44. if (val && (typeof val === 'object' || typeof val === 'function')) {
  45. var then = val.then;
  46. if (typeof then === 'function') {
  47. then.call(
  48. val,
  49. function(val) {
  50. res(i, val);
  51. },
  52. function(e) {
  53. args[i] = { status: 'rejected', reason: e };
  54. if (--remaining === 0) {
  55. resolve(args);
  56. }
  57. }
  58. );
  59. return;
  60. }
  61. }
  62. args[i] = { status: 'fulfilled', value: val };
  63. if (--remaining === 0) {
  64. resolve(args);
  65. }
  66. }
  67. for (var i = 0; i < args.length; i++) {
  68. res(i, args[i]);
  69. }
  70. });
  71. }
  72. /**
  73. * @constructor
  74. */
  75. function AggregateError(errors, message) {
  76. this.name = 'AggregateError', this.errors = errors;
  77. this.message = message || '';
  78. }
  79. AggregateError.prototype = Error.prototype;
  80. function any(arr) {
  81. var P = this;
  82. return new P(function(resolve, reject) {
  83. if (!(arr && typeof arr.length !== 'undefined')) {
  84. return reject(new TypeError('Promise.any accepts an array'));
  85. }
  86. var args = Array.prototype.slice.call(arr);
  87. if (args.length === 0) return reject();
  88. var rejectionReasons = [];
  89. for (var i = 0; i < args.length; i++) {
  90. try {
  91. P.resolve(args[i])
  92. .then(resolve)
  93. .catch(function(error) {
  94. rejectionReasons.push(error);
  95. if (rejectionReasons.length === args.length) {
  96. reject(
  97. new AggregateError(
  98. rejectionReasons,
  99. 'All promises were rejected'
  100. )
  101. );
  102. }
  103. });
  104. } catch (ex) {
  105. reject(ex);
  106. }
  107. }
  108. });
  109. }
  110. // Store setTimeout reference so promise-polyfill will be unaffected by
  111. // other code modifying setTimeout (like sinon.useFakeTimers())
  112. var setTimeoutFunc = setTimeout;
  113. function isArray(x) {
  114. return Boolean(x && typeof x.length !== 'undefined');
  115. }
  116. function noop() {}
  117. // Polyfill for Function.prototype.bind
  118. function bind(fn, thisArg) {
  119. return function() {
  120. fn.apply(thisArg, arguments);
  121. };
  122. }
  123. /**
  124. * @constructor
  125. * @param {Function} fn
  126. */
  127. function Promise(fn) {
  128. if (!(this instanceof Promise))
  129. throw new TypeError('Promises must be constructed via new');
  130. if (typeof fn !== 'function') throw new TypeError('not a function');
  131. /** @type {!number} */
  132. this._state = 0;
  133. /** @type {!boolean} */
  134. this._handled = false;
  135. /** @type {Promise|undefined} */
  136. this._value = undefined;
  137. /** @type {!Array<!Function>} */
  138. this._deferreds = [];
  139. doResolve(fn, this);
  140. }
  141. function handle(self, deferred) {
  142. while (self._state === 3) {
  143. self = self._value;
  144. }
  145. if (self._state === 0) {
  146. self._deferreds.push(deferred);
  147. return;
  148. }
  149. self._handled = true;
  150. Promise._immediateFn(function() {
  151. var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
  152. if (cb === null) {
  153. (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
  154. return;
  155. }
  156. var ret;
  157. try {
  158. ret = cb(self._value);
  159. } catch (e) {
  160. reject(deferred.promise, e);
  161. return;
  162. }
  163. resolve(deferred.promise, ret);
  164. });
  165. }
  166. function resolve(self, newValue) {
  167. try {
  168. // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
  169. if (newValue === self)
  170. throw new TypeError('A promise cannot be resolved with itself.');
  171. if (
  172. newValue &&
  173. (typeof newValue === 'object' || typeof newValue === 'function')
  174. ) {
  175. var then = newValue.then;
  176. if (newValue instanceof Promise) {
  177. self._state = 3;
  178. self._value = newValue;
  179. finale(self);
  180. return;
  181. } else if (typeof then === 'function') {
  182. doResolve(bind(then, newValue), self);
  183. return;
  184. }
  185. }
  186. self._state = 1;
  187. self._value = newValue;
  188. finale(self);
  189. } catch (e) {
  190. reject(self, e);
  191. }
  192. }
  193. function reject(self, newValue) {
  194. self._state = 2;
  195. self._value = newValue;
  196. finale(self);
  197. }
  198. function finale(self) {
  199. if (self._state === 2 && self._deferreds.length === 0) {
  200. Promise._immediateFn(function() {
  201. if (!self._handled) {
  202. Promise._unhandledRejectionFn(self._value);
  203. }
  204. });
  205. }
  206. for (var i = 0, len = self._deferreds.length; i < len; i++) {
  207. handle(self, self._deferreds[i]);
  208. }
  209. self._deferreds = null;
  210. }
  211. /**
  212. * @constructor
  213. */
  214. function Handler(onFulfilled, onRejected, promise) {
  215. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  216. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  217. this.promise = promise;
  218. }
  219. /**
  220. * Take a potentially misbehaving resolver function and make sure
  221. * onFulfilled and onRejected are only called once.
  222. *
  223. * Makes no guarantees about asynchrony.
  224. */
  225. function doResolve(fn, self) {
  226. var done = false;
  227. try {
  228. fn(
  229. function(value) {
  230. if (done) return;
  231. done = true;
  232. resolve(self, value);
  233. },
  234. function(reason) {
  235. if (done) return;
  236. done = true;
  237. reject(self, reason);
  238. }
  239. );
  240. } catch (ex) {
  241. if (done) return;
  242. done = true;
  243. reject(self, ex);
  244. }
  245. }
  246. Promise.prototype['catch'] = function(onRejected) {
  247. return this.then(null, onRejected);
  248. };
  249. Promise.prototype.then = function(onFulfilled, onRejected) {
  250. // @ts-ignore
  251. var prom = new this.constructor(noop);
  252. handle(this, new Handler(onFulfilled, onRejected, prom));
  253. return prom;
  254. };
  255. Promise.prototype['finally'] = finallyConstructor;
  256. Promise.all = function(arr) {
  257. return new Promise(function(resolve, reject) {
  258. if (!isArray(arr)) {
  259. return reject(new TypeError('Promise.all accepts an array'));
  260. }
  261. var args = Array.prototype.slice.call(arr);
  262. if (args.length === 0) return resolve([]);
  263. var remaining = args.length;
  264. function res(i, val) {
  265. try {
  266. if (val && (typeof val === 'object' || typeof val === 'function')) {
  267. var then = val.then;
  268. if (typeof then === 'function') {
  269. then.call(
  270. val,
  271. function(val) {
  272. res(i, val);
  273. },
  274. reject
  275. );
  276. return;
  277. }
  278. }
  279. args[i] = val;
  280. if (--remaining === 0) {
  281. resolve(args);
  282. }
  283. } catch (ex) {
  284. reject(ex);
  285. }
  286. }
  287. for (var i = 0; i < args.length; i++) {
  288. res(i, args[i]);
  289. }
  290. });
  291. };
  292. Promise.any = any;
  293. Promise.allSettled = allSettled;
  294. Promise.resolve = function(value) {
  295. if (value && typeof value === 'object' && value.constructor === Promise) {
  296. return value;
  297. }
  298. return new Promise(function(resolve) {
  299. resolve(value);
  300. });
  301. };
  302. Promise.reject = function(value) {
  303. return new Promise(function(resolve, reject) {
  304. reject(value);
  305. });
  306. };
  307. Promise.race = function(arr) {
  308. return new Promise(function(resolve, reject) {
  309. if (!isArray(arr)) {
  310. return reject(new TypeError('Promise.race accepts an array'));
  311. }
  312. for (var i = 0, len = arr.length; i < len; i++) {
  313. Promise.resolve(arr[i]).then(resolve, reject);
  314. }
  315. });
  316. };
  317. // Use polyfill for setImmediate for performance gains
  318. Promise._immediateFn =
  319. // @ts-ignore
  320. (typeof setImmediate === 'function' &&
  321. function(fn) {
  322. // @ts-ignore
  323. setImmediate(fn);
  324. }) ||
  325. function(fn) {
  326. setTimeoutFunc(fn, 0);
  327. };
  328. Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  329. if (typeof console !== 'undefined' && console) {
  330. console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console
  331. }
  332. };
  333. /** @suppress {undefinedVars} */
  334. var globalNS = (function() {
  335. // the only reliable means to get the global object is
  336. // `Function('return this')()`
  337. // However, this causes CSP violations in Chrome apps.
  338. if (typeof self !== 'undefined') {
  339. return self;
  340. }
  341. if (typeof window !== 'undefined') {
  342. return window;
  343. }
  344. if (typeof global !== 'undefined') {
  345. return global;
  346. }
  347. throw new Error('unable to locate global object');
  348. })();
  349. // Expose the polyfill if Promise is undefined or set to a
  350. // non-function value. The latter can be due to a named HTMLElement
  351. // being exposed by browsers for legacy reasons.
  352. // https://github.com/taylorhakes/promise-polyfill/issues/114
  353. if (typeof globalNS['Promise'] !== 'function') {
  354. globalNS['Promise'] = Promise;
  355. } else {
  356. if (!globalNS.Promise.prototype['finally']) {
  357. globalNS.Promise.prototype['finally'] = finallyConstructor;
  358. }
  359. if (!globalNS.Promise.allSettled) {
  360. globalNS.Promise.allSettled = allSettled;
  361. }
  362. if (!globalNS.Promise.any) {
  363. globalNS.Promise.any = any;
  364. }
  365. }
  366. })));