index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. /* jshint node: true */
  2. "use strict";
  3. function makeArrayFrom(obj) {
  4. return Array.prototype.slice.apply(obj);
  5. }
  6. var
  7. PENDING = "pending",
  8. RESOLVED = "resolved",
  9. REJECTED = "rejected";
  10. function SynchronousPromise(handler) {
  11. this.status = PENDING;
  12. this._continuations = [];
  13. this._parent = null;
  14. this._paused = false;
  15. if (handler) {
  16. handler.call(
  17. this,
  18. this._continueWith.bind(this),
  19. this._failWith.bind(this)
  20. );
  21. }
  22. }
  23. function looksLikeAPromise(obj) {
  24. return obj && typeof (obj.then) === "function";
  25. }
  26. function passThrough(value) {
  27. return value;
  28. }
  29. SynchronousPromise.prototype = {
  30. then: function (nextFn, catchFn) {
  31. var next = SynchronousPromise.unresolved()._setParent(this);
  32. if (this._isRejected()) {
  33. if (this._paused) {
  34. this._continuations.push({
  35. promise: next,
  36. nextFn: nextFn,
  37. catchFn: catchFn
  38. });
  39. return next;
  40. }
  41. if (catchFn) {
  42. try {
  43. var catchResult = catchFn(this._error);
  44. if (looksLikeAPromise(catchResult)) {
  45. this._chainPromiseData(catchResult, next);
  46. return next;
  47. } else {
  48. return SynchronousPromise.resolve(catchResult)._setParent(this);
  49. }
  50. } catch (e) {
  51. return SynchronousPromise.reject(e)._setParent(this);
  52. }
  53. }
  54. return SynchronousPromise.reject(this._error)._setParent(this);
  55. }
  56. this._continuations.push({
  57. promise: next,
  58. nextFn: nextFn,
  59. catchFn: catchFn
  60. });
  61. this._runResolutions();
  62. return next;
  63. },
  64. catch: function (handler) {
  65. if (this._isResolved()) {
  66. return SynchronousPromise.resolve(this._data)._setParent(this);
  67. }
  68. var next = SynchronousPromise.unresolved()._setParent(this);
  69. this._continuations.push({
  70. promise: next,
  71. catchFn: handler
  72. });
  73. this._runRejections();
  74. return next;
  75. },
  76. finally: function (callback) {
  77. var ran = false;
  78. function runFinally(result, err) {
  79. if (!ran) {
  80. ran = true;
  81. if (!callback) {
  82. callback = passThrough;
  83. }
  84. var callbackResult = callback(result);
  85. if (looksLikeAPromise(callbackResult)) {
  86. return callbackResult.then(function () {
  87. if (err) {
  88. throw err;
  89. }
  90. return result;
  91. });
  92. } else {
  93. return result;
  94. }
  95. }
  96. }
  97. return this
  98. .then(function (result) {
  99. return runFinally(result);
  100. })
  101. .catch(function (err) {
  102. return runFinally(null, err);
  103. });
  104. },
  105. pause: function () {
  106. this._paused = true;
  107. return this;
  108. },
  109. resume: function () {
  110. var firstPaused = this._findFirstPaused();
  111. if (firstPaused) {
  112. firstPaused._paused = false;
  113. firstPaused._runResolutions();
  114. firstPaused._runRejections();
  115. }
  116. return this;
  117. },
  118. _findAncestry: function () {
  119. return this._continuations.reduce(function (acc, cur) {
  120. if (cur.promise) {
  121. var node = {
  122. promise: cur.promise,
  123. children: cur.promise._findAncestry()
  124. };
  125. acc.push(node);
  126. }
  127. return acc;
  128. }, []);
  129. },
  130. _setParent: function (parent) {
  131. if (this._parent) {
  132. throw new Error("parent already set");
  133. }
  134. this._parent = parent;
  135. return this;
  136. },
  137. _continueWith: function (data) {
  138. var firstPending = this._findFirstPending();
  139. if (firstPending) {
  140. firstPending._data = data;
  141. firstPending._setResolved();
  142. }
  143. },
  144. _findFirstPending: function () {
  145. return this._findFirstAncestor(function (test) {
  146. return test._isPending && test._isPending();
  147. });
  148. },
  149. _findFirstPaused: function () {
  150. return this._findFirstAncestor(function (test) {
  151. return test._paused;
  152. });
  153. },
  154. _findFirstAncestor: function (matching) {
  155. var test = this;
  156. var result;
  157. while (test) {
  158. if (matching(test)) {
  159. result = test;
  160. }
  161. test = test._parent;
  162. }
  163. return result;
  164. },
  165. _failWith: function (error) {
  166. var firstRejected = this._findFirstPending();
  167. if (firstRejected) {
  168. firstRejected._error = error;
  169. firstRejected._setRejected();
  170. }
  171. },
  172. _takeContinuations: function () {
  173. return this._continuations.splice(0, this._continuations.length);
  174. },
  175. _runRejections: function () {
  176. if (this._paused || !this._isRejected()) {
  177. return;
  178. }
  179. var
  180. error = this._error,
  181. continuations = this._takeContinuations(),
  182. self = this;
  183. continuations.forEach(function (cont) {
  184. if (cont.catchFn) {
  185. try {
  186. var catchResult = cont.catchFn(error);
  187. self._handleUserFunctionResult(catchResult, cont.promise);
  188. } catch (e) {
  189. cont.promise.reject(e);
  190. }
  191. } else {
  192. cont.promise.reject(error);
  193. }
  194. });
  195. },
  196. _runResolutions: function () {
  197. if (this._paused || !this._isResolved() || this._isPending()) {
  198. return;
  199. }
  200. var continuations = this._takeContinuations();
  201. var data = this._data;
  202. var self = this;
  203. continuations.forEach(function (cont) {
  204. if (cont.nextFn) {
  205. try {
  206. var result = cont.nextFn(data);
  207. self._handleUserFunctionResult(result, cont.promise);
  208. } catch (e) {
  209. self._handleResolutionError(e, cont);
  210. }
  211. } else if (cont.promise) {
  212. cont.promise.resolve(data);
  213. }
  214. });
  215. if (looksLikeAPromise(this._data)) {
  216. return this._handleWhenResolvedDataIsPromise(this._data);
  217. }
  218. },
  219. _handleResolutionError: function (e, continuation) {
  220. this._setRejected();
  221. if (continuation.catchFn) {
  222. try {
  223. continuation.catchFn(e);
  224. return;
  225. } catch (e2) {
  226. e = e2;
  227. }
  228. }
  229. if (continuation.promise) {
  230. continuation.promise.reject(e);
  231. }
  232. },
  233. _handleWhenResolvedDataIsPromise: function (data) {
  234. var self = this;
  235. return data.then(function (result) {
  236. self._data = result;
  237. self._runResolutions();
  238. }).catch(function (error) {
  239. self._error = error;
  240. self._setRejected();
  241. self._runRejections();
  242. });
  243. },
  244. _handleUserFunctionResult: function (data, nextSynchronousPromise) {
  245. if (looksLikeAPromise(data)) {
  246. this._chainPromiseData(data, nextSynchronousPromise);
  247. } else {
  248. nextSynchronousPromise.resolve(data);
  249. }
  250. },
  251. _chainPromiseData: function (promiseData, nextSynchronousPromise) {
  252. promiseData.then(function (newData) {
  253. nextSynchronousPromise.resolve(newData);
  254. }).catch(function (newError) {
  255. nextSynchronousPromise.reject(newError);
  256. });
  257. },
  258. _setResolved: function () {
  259. this.status = RESOLVED;
  260. if (!this._paused) {
  261. this._runResolutions();
  262. }
  263. },
  264. _setRejected: function () {
  265. this.status = REJECTED;
  266. if (!this._paused) {
  267. this._runRejections();
  268. }
  269. },
  270. _isPending: function () {
  271. return this.status === PENDING;
  272. },
  273. _isResolved: function () {
  274. return this.status === RESOLVED;
  275. },
  276. _isRejected: function () {
  277. return this.status === REJECTED;
  278. }
  279. };
  280. SynchronousPromise.resolve = function (result) {
  281. return new SynchronousPromise(function (resolve, reject) {
  282. if (looksLikeAPromise(result)) {
  283. result.then(function (newResult) {
  284. resolve(newResult);
  285. }).catch(function (error) {
  286. reject(error);
  287. });
  288. } else {
  289. resolve(result);
  290. }
  291. });
  292. };
  293. SynchronousPromise.reject = function (result) {
  294. return new SynchronousPromise(function (resolve, reject) {
  295. reject(result);
  296. });
  297. };
  298. SynchronousPromise.unresolved = function () {
  299. return new SynchronousPromise(function (resolve, reject) {
  300. this.resolve = resolve;
  301. this.reject = reject;
  302. });
  303. };
  304. SynchronousPromise.all = function () {
  305. var args = makeArrayFrom(arguments);
  306. if (Array.isArray(args[0])) {
  307. args = args[0];
  308. }
  309. if (!args.length) {
  310. return SynchronousPromise.resolve([]);
  311. }
  312. return new SynchronousPromise(function (resolve, reject) {
  313. var
  314. allData = [],
  315. numResolved = 0,
  316. doResolve = function () {
  317. if (numResolved === args.length) {
  318. resolve(allData);
  319. }
  320. },
  321. rejected = false,
  322. doReject = function (err) {
  323. if (rejected) {
  324. return;
  325. }
  326. rejected = true;
  327. reject(err);
  328. };
  329. args.forEach(function (arg, idx) {
  330. SynchronousPromise.resolve(arg).then(function (thisResult) {
  331. allData[idx] = thisResult;
  332. numResolved += 1;
  333. doResolve();
  334. }).catch(function (err) {
  335. doReject(err);
  336. });
  337. });
  338. });
  339. };
  340. function createAggregateErrorFrom(errors) {
  341. /* jshint ignore:start */
  342. if (typeof window !== "undefined" && "AggregateError" in window) {
  343. return new window.AggregateError(errors);
  344. }
  345. /* jshint ignore:end */
  346. return { errors: errors };
  347. }
  348. SynchronousPromise.any = function () {
  349. var args = makeArrayFrom(arguments);
  350. if (Array.isArray(args[0])) {
  351. args = args[0];
  352. }
  353. if (!args.length) {
  354. return SynchronousPromise.reject(createAggregateErrorFrom([]));
  355. }
  356. return new SynchronousPromise(function (resolve, reject) {
  357. var
  358. allErrors = [],
  359. numRejected = 0,
  360. doReject = function () {
  361. if (numRejected === args.length) {
  362. reject(createAggregateErrorFrom(allErrors));
  363. }
  364. },
  365. resolved = false,
  366. doResolve = function (result) {
  367. if (resolved) {
  368. return;
  369. }
  370. resolved = true;
  371. resolve(result);
  372. };
  373. args.forEach(function (arg, idx) {
  374. SynchronousPromise.resolve(arg).then(function (thisResult) {
  375. doResolve(thisResult);
  376. }).catch(function (err) {
  377. allErrors[idx] = err;
  378. numRejected += 1;
  379. doReject();
  380. });
  381. });
  382. });
  383. };
  384. SynchronousPromise.allSettled = function () {
  385. var args = makeArrayFrom(arguments);
  386. if (Array.isArray(args[0])) {
  387. args = args[0];
  388. }
  389. if (!args.length) {
  390. return SynchronousPromise.resolve([]);
  391. }
  392. return new SynchronousPromise(function (resolve) {
  393. var
  394. allData = [],
  395. numSettled = 0,
  396. doSettled = function () {
  397. numSettled += 1;
  398. if (numSettled === args.length) {
  399. resolve(allData);
  400. }
  401. };
  402. args.forEach(function (arg, idx) {
  403. SynchronousPromise.resolve(arg).then(function (thisResult) {
  404. allData[idx] = {
  405. status: "fulfilled",
  406. value: thisResult
  407. };
  408. doSettled();
  409. }).catch(function (err) {
  410. allData[idx] = {
  411. status: "rejected",
  412. reason: err
  413. };
  414. doSettled();
  415. });
  416. });
  417. });
  418. };
  419. /* jshint ignore:start */
  420. if (Promise === SynchronousPromise) {
  421. throw new Error("Please use SynchronousPromise.installGlobally() to install globally");
  422. }
  423. var RealPromise = Promise;
  424. SynchronousPromise.installGlobally = function (__awaiter) {
  425. if (Promise === SynchronousPromise) {
  426. return __awaiter;
  427. }
  428. var result = patchAwaiterIfRequired(__awaiter);
  429. Promise = SynchronousPromise;
  430. return result;
  431. };
  432. SynchronousPromise.uninstallGlobally = function () {
  433. if (Promise === SynchronousPromise) {
  434. Promise = RealPromise;
  435. }
  436. };
  437. function patchAwaiterIfRequired(__awaiter) {
  438. if (typeof (__awaiter) === "undefined" || __awaiter.__patched) {
  439. return __awaiter;
  440. }
  441. var originalAwaiter = __awaiter;
  442. __awaiter = function () {
  443. var Promise = RealPromise;
  444. originalAwaiter.apply(this, makeArrayFrom(arguments));
  445. };
  446. __awaiter.__patched = true;
  447. return __awaiter;
  448. }
  449. /* jshint ignore:end */
  450. module.exports = {
  451. SynchronousPromise: SynchronousPromise
  452. };