async.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. /*---------------------------------------------------------------------------------------------
  2. * Copyright (c) Microsoft Corporation. All rights reserved.
  3. * Licensed under the MIT License. See License.txt in the project root for license information.
  4. *--------------------------------------------------------------------------------------------*/
  5. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  6. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  7. return new (P || (P = Promise))(function (resolve, reject) {
  8. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  9. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  10. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  11. step((generator = generator.apply(thisArg, _arguments || [])).next());
  12. });
  13. };
  14. import { CancellationTokenSource } from './cancellation.js';
  15. import { canceled } from './errors.js';
  16. import { toDisposable } from './lifecycle.js';
  17. export function isThenable(obj) {
  18. return !!obj && typeof obj.then === 'function';
  19. }
  20. export function createCancelablePromise(callback) {
  21. const source = new CancellationTokenSource();
  22. const thenable = callback(source.token);
  23. const promise = new Promise((resolve, reject) => {
  24. const subscription = source.token.onCancellationRequested(() => {
  25. subscription.dispose();
  26. source.dispose();
  27. reject(canceled());
  28. });
  29. Promise.resolve(thenable).then(value => {
  30. subscription.dispose();
  31. source.dispose();
  32. resolve(value);
  33. }, err => {
  34. subscription.dispose();
  35. source.dispose();
  36. reject(err);
  37. });
  38. });
  39. return new class {
  40. cancel() {
  41. source.cancel();
  42. }
  43. then(resolve, reject) {
  44. return promise.then(resolve, reject);
  45. }
  46. catch(reject) {
  47. return this.then(undefined, reject);
  48. }
  49. finally(onfinally) {
  50. return promise.finally(onfinally);
  51. }
  52. };
  53. }
  54. export function raceCancellation(promise, token, defaultValue) {
  55. return Promise.race([promise, new Promise(resolve => token.onCancellationRequested(() => resolve(defaultValue)))]);
  56. }
  57. /**
  58. * A helper to prevent accumulation of sequential async tasks.
  59. *
  60. * Imagine a mail man with the sole task of delivering letters. As soon as
  61. * a letter submitted for delivery, he drives to the destination, delivers it
  62. * and returns to his base. Imagine that during the trip, N more letters were submitted.
  63. * When the mail man returns, he picks those N letters and delivers them all in a
  64. * single trip. Even though N+1 submissions occurred, only 2 deliveries were made.
  65. *
  66. * The throttler implements this via the queue() method, by providing it a task
  67. * factory. Following the example:
  68. *
  69. * const throttler = new Throttler();
  70. * const letters = [];
  71. *
  72. * function deliver() {
  73. * const lettersToDeliver = letters;
  74. * letters = [];
  75. * return makeTheTrip(lettersToDeliver);
  76. * }
  77. *
  78. * function onLetterReceived(l) {
  79. * letters.push(l);
  80. * throttler.queue(deliver);
  81. * }
  82. */
  83. export class Throttler {
  84. constructor() {
  85. this.activePromise = null;
  86. this.queuedPromise = null;
  87. this.queuedPromiseFactory = null;
  88. }
  89. queue(promiseFactory) {
  90. if (this.activePromise) {
  91. this.queuedPromiseFactory = promiseFactory;
  92. if (!this.queuedPromise) {
  93. const onComplete = () => {
  94. this.queuedPromise = null;
  95. const result = this.queue(this.queuedPromiseFactory);
  96. this.queuedPromiseFactory = null;
  97. return result;
  98. };
  99. this.queuedPromise = new Promise(resolve => {
  100. this.activePromise.then(onComplete, onComplete).then(resolve);
  101. });
  102. }
  103. return new Promise((resolve, reject) => {
  104. this.queuedPromise.then(resolve, reject);
  105. });
  106. }
  107. this.activePromise = promiseFactory();
  108. return new Promise((resolve, reject) => {
  109. this.activePromise.then((result) => {
  110. this.activePromise = null;
  111. resolve(result);
  112. }, (err) => {
  113. this.activePromise = null;
  114. reject(err);
  115. });
  116. });
  117. }
  118. }
  119. /**
  120. * A helper to delay (debounce) execution of a task that is being requested often.
  121. *
  122. * Following the throttler, now imagine the mail man wants to optimize the number of
  123. * trips proactively. The trip itself can be long, so he decides not to make the trip
  124. * as soon as a letter is submitted. Instead he waits a while, in case more
  125. * letters are submitted. After said waiting period, if no letters were submitted, he
  126. * decides to make the trip. Imagine that N more letters were submitted after the first
  127. * one, all within a short period of time between each other. Even though N+1
  128. * submissions occurred, only 1 delivery was made.
  129. *
  130. * The delayer offers this behavior via the trigger() method, into which both the task
  131. * to be executed and the waiting period (delay) must be passed in as arguments. Following
  132. * the example:
  133. *
  134. * const delayer = new Delayer(WAITING_PERIOD);
  135. * const letters = [];
  136. *
  137. * function letterReceived(l) {
  138. * letters.push(l);
  139. * delayer.trigger(() => { return makeTheTrip(); });
  140. * }
  141. */
  142. export class Delayer {
  143. constructor(defaultDelay) {
  144. this.defaultDelay = defaultDelay;
  145. this.timeout = null;
  146. this.completionPromise = null;
  147. this.doResolve = null;
  148. this.doReject = null;
  149. this.task = null;
  150. }
  151. trigger(task, delay = this.defaultDelay) {
  152. this.task = task;
  153. this.cancelTimeout();
  154. if (!this.completionPromise) {
  155. this.completionPromise = new Promise((resolve, reject) => {
  156. this.doResolve = resolve;
  157. this.doReject = reject;
  158. }).then(() => {
  159. this.completionPromise = null;
  160. this.doResolve = null;
  161. if (this.task) {
  162. const task = this.task;
  163. this.task = null;
  164. return task();
  165. }
  166. return undefined;
  167. });
  168. }
  169. this.timeout = setTimeout(() => {
  170. this.timeout = null;
  171. if (this.doResolve) {
  172. this.doResolve(null);
  173. }
  174. }, delay);
  175. return this.completionPromise;
  176. }
  177. isTriggered() {
  178. return this.timeout !== null;
  179. }
  180. cancel() {
  181. this.cancelTimeout();
  182. if (this.completionPromise) {
  183. if (this.doReject) {
  184. this.doReject(canceled());
  185. }
  186. this.completionPromise = null;
  187. }
  188. }
  189. cancelTimeout() {
  190. if (this.timeout !== null) {
  191. clearTimeout(this.timeout);
  192. this.timeout = null;
  193. }
  194. }
  195. dispose() {
  196. this.cancel();
  197. }
  198. }
  199. /**
  200. * A helper to delay execution of a task that is being requested often, while
  201. * preventing accumulation of consecutive executions, while the task runs.
  202. *
  203. * The mail man is clever and waits for a certain amount of time, before going
  204. * out to deliver letters. While the mail man is going out, more letters arrive
  205. * and can only be delivered once he is back. Once he is back the mail man will
  206. * do one more trip to deliver the letters that have accumulated while he was out.
  207. */
  208. export class ThrottledDelayer {
  209. constructor(defaultDelay) {
  210. this.delayer = new Delayer(defaultDelay);
  211. this.throttler = new Throttler();
  212. }
  213. trigger(promiseFactory, delay) {
  214. return this.delayer.trigger(() => this.throttler.queue(promiseFactory), delay);
  215. }
  216. dispose() {
  217. this.delayer.dispose();
  218. }
  219. }
  220. export function timeout(millis, token) {
  221. if (!token) {
  222. return createCancelablePromise(token => timeout(millis, token));
  223. }
  224. return new Promise((resolve, reject) => {
  225. const handle = setTimeout(() => {
  226. disposable.dispose();
  227. resolve();
  228. }, millis);
  229. const disposable = token.onCancellationRequested(() => {
  230. clearTimeout(handle);
  231. disposable.dispose();
  232. reject(canceled());
  233. });
  234. });
  235. }
  236. export function disposableTimeout(handler, timeout = 0) {
  237. const timer = setTimeout(handler, timeout);
  238. return toDisposable(() => clearTimeout(timer));
  239. }
  240. export function first(promiseFactories, shouldStop = t => !!t, defaultValue = null) {
  241. let index = 0;
  242. const len = promiseFactories.length;
  243. const loop = () => {
  244. if (index >= len) {
  245. return Promise.resolve(defaultValue);
  246. }
  247. const factory = promiseFactories[index++];
  248. const promise = Promise.resolve(factory());
  249. return promise.then(result => {
  250. if (shouldStop(result)) {
  251. return Promise.resolve(result);
  252. }
  253. return loop();
  254. });
  255. };
  256. return loop();
  257. }
  258. export class TimeoutTimer {
  259. constructor(runner, timeout) {
  260. this._token = -1;
  261. if (typeof runner === 'function' && typeof timeout === 'number') {
  262. this.setIfNotSet(runner, timeout);
  263. }
  264. }
  265. dispose() {
  266. this.cancel();
  267. }
  268. cancel() {
  269. if (this._token !== -1) {
  270. clearTimeout(this._token);
  271. this._token = -1;
  272. }
  273. }
  274. cancelAndSet(runner, timeout) {
  275. this.cancel();
  276. this._token = setTimeout(() => {
  277. this._token = -1;
  278. runner();
  279. }, timeout);
  280. }
  281. setIfNotSet(runner, timeout) {
  282. if (this._token !== -1) {
  283. // timer is already set
  284. return;
  285. }
  286. this._token = setTimeout(() => {
  287. this._token = -1;
  288. runner();
  289. }, timeout);
  290. }
  291. }
  292. export class IntervalTimer {
  293. constructor() {
  294. this._token = -1;
  295. }
  296. dispose() {
  297. this.cancel();
  298. }
  299. cancel() {
  300. if (this._token !== -1) {
  301. clearInterval(this._token);
  302. this._token = -1;
  303. }
  304. }
  305. cancelAndSet(runner, interval) {
  306. this.cancel();
  307. this._token = setInterval(() => {
  308. runner();
  309. }, interval);
  310. }
  311. }
  312. export class RunOnceScheduler {
  313. constructor(runner, delay) {
  314. this.timeoutToken = -1;
  315. this.runner = runner;
  316. this.timeout = delay;
  317. this.timeoutHandler = this.onTimeout.bind(this);
  318. }
  319. /**
  320. * Dispose RunOnceScheduler
  321. */
  322. dispose() {
  323. this.cancel();
  324. this.runner = null;
  325. }
  326. /**
  327. * Cancel current scheduled runner (if any).
  328. */
  329. cancel() {
  330. if (this.isScheduled()) {
  331. clearTimeout(this.timeoutToken);
  332. this.timeoutToken = -1;
  333. }
  334. }
  335. /**
  336. * Cancel previous runner (if any) & schedule a new runner.
  337. */
  338. schedule(delay = this.timeout) {
  339. this.cancel();
  340. this.timeoutToken = setTimeout(this.timeoutHandler, delay);
  341. }
  342. get delay() {
  343. return this.timeout;
  344. }
  345. set delay(value) {
  346. this.timeout = value;
  347. }
  348. /**
  349. * Returns true if scheduled.
  350. */
  351. isScheduled() {
  352. return this.timeoutToken !== -1;
  353. }
  354. onTimeout() {
  355. this.timeoutToken = -1;
  356. if (this.runner) {
  357. this.doRun();
  358. }
  359. }
  360. doRun() {
  361. if (this.runner) {
  362. this.runner();
  363. }
  364. }
  365. }
  366. /**
  367. * Execute the callback the next time the browser is idle
  368. */
  369. export let runWhenIdle;
  370. (function () {
  371. if (typeof requestIdleCallback !== 'function' || typeof cancelIdleCallback !== 'function') {
  372. const dummyIdle = Object.freeze({
  373. didTimeout: true,
  374. timeRemaining() { return 15; }
  375. });
  376. runWhenIdle = (runner) => {
  377. const handle = setTimeout(() => runner(dummyIdle));
  378. let disposed = false;
  379. return {
  380. dispose() {
  381. if (disposed) {
  382. return;
  383. }
  384. disposed = true;
  385. clearTimeout(handle);
  386. }
  387. };
  388. };
  389. }
  390. else {
  391. runWhenIdle = (runner, timeout) => {
  392. const handle = requestIdleCallback(runner, typeof timeout === 'number' ? { timeout } : undefined);
  393. let disposed = false;
  394. return {
  395. dispose() {
  396. if (disposed) {
  397. return;
  398. }
  399. disposed = true;
  400. cancelIdleCallback(handle);
  401. }
  402. };
  403. };
  404. }
  405. })();
  406. /**
  407. * An implementation of the "idle-until-urgent"-strategy as introduced
  408. * here: https://philipwalton.com/articles/idle-until-urgent/
  409. */
  410. export class IdleValue {
  411. constructor(executor) {
  412. this._didRun = false;
  413. this._executor = () => {
  414. try {
  415. this._value = executor();
  416. }
  417. catch (err) {
  418. this._error = err;
  419. }
  420. finally {
  421. this._didRun = true;
  422. }
  423. };
  424. this._handle = runWhenIdle(() => this._executor());
  425. }
  426. dispose() {
  427. this._handle.dispose();
  428. }
  429. get value() {
  430. if (!this._didRun) {
  431. this._handle.dispose();
  432. this._executor();
  433. }
  434. if (this._error) {
  435. throw this._error;
  436. }
  437. return this._value;
  438. }
  439. get isInitialized() {
  440. return this._didRun;
  441. }
  442. }
  443. //#endregion
  444. //#region Promises
  445. export var Promises;
  446. (function (Promises) {
  447. /**
  448. * A drop-in replacement for `Promise.all` with the only difference
  449. * that the method awaits every promise to either fulfill or reject.
  450. *
  451. * Similar to `Promise.all`, only the first error will be returned
  452. * if any.
  453. */
  454. function settled(promises) {
  455. return __awaiter(this, void 0, void 0, function* () {
  456. let firstError = undefined;
  457. const result = yield Promise.all(promises.map(promise => promise.then(value => value, error => {
  458. if (!firstError) {
  459. firstError = error;
  460. }
  461. return undefined; // do not rethrow so that other promises can settle
  462. })));
  463. if (typeof firstError !== 'undefined') {
  464. throw firstError;
  465. }
  466. return result; // cast is needed and protected by the `throw` above
  467. });
  468. }
  469. Promises.settled = settled;
  470. })(Promises || (Promises = {}));
  471. //#endregion