async.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887
  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. var __asyncValues = (this && this.__asyncValues) || function (o) {
  15. if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  16. var m = o[Symbol.asyncIterator], i;
  17. return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
  18. function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
  19. function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
  20. };
  21. import { CancellationTokenSource } from './cancellation.js';
  22. import { CancellationError } from './errors.js';
  23. import { Emitter, Event } from './event.js';
  24. import { toDisposable } from './lifecycle.js';
  25. import { setTimeout0 } from './platform.js';
  26. import { MicrotaskDelay } from './symbols.js';
  27. export function isThenable(obj) {
  28. return !!obj && typeof obj.then === 'function';
  29. }
  30. export function createCancelablePromise(callback) {
  31. const source = new CancellationTokenSource();
  32. const thenable = callback(source.token);
  33. const promise = new Promise((resolve, reject) => {
  34. const subscription = source.token.onCancellationRequested(() => {
  35. subscription.dispose();
  36. source.dispose();
  37. reject(new CancellationError());
  38. });
  39. Promise.resolve(thenable).then(value => {
  40. subscription.dispose();
  41. source.dispose();
  42. resolve(value);
  43. }, err => {
  44. subscription.dispose();
  45. source.dispose();
  46. reject(err);
  47. });
  48. });
  49. return new class {
  50. cancel() {
  51. source.cancel();
  52. }
  53. then(resolve, reject) {
  54. return promise.then(resolve, reject);
  55. }
  56. catch(reject) {
  57. return this.then(undefined, reject);
  58. }
  59. finally(onfinally) {
  60. return promise.finally(onfinally);
  61. }
  62. };
  63. }
  64. export function raceCancellation(promise, token, defaultValue) {
  65. return new Promise((resolve, reject) => {
  66. const ref = token.onCancellationRequested(() => {
  67. ref.dispose();
  68. resolve(defaultValue);
  69. });
  70. promise.then(resolve, reject).finally(() => ref.dispose());
  71. });
  72. }
  73. /**
  74. * A helper to prevent accumulation of sequential async tasks.
  75. *
  76. * Imagine a mail man with the sole task of delivering letters. As soon as
  77. * a letter submitted for delivery, he drives to the destination, delivers it
  78. * and returns to his base. Imagine that during the trip, N more letters were submitted.
  79. * When the mail man returns, he picks those N letters and delivers them all in a
  80. * single trip. Even though N+1 submissions occurred, only 2 deliveries were made.
  81. *
  82. * The throttler implements this via the queue() method, by providing it a task
  83. * factory. Following the example:
  84. *
  85. * const throttler = new Throttler();
  86. * const letters = [];
  87. *
  88. * function deliver() {
  89. * const lettersToDeliver = letters;
  90. * letters = [];
  91. * return makeTheTrip(lettersToDeliver);
  92. * }
  93. *
  94. * function onLetterReceived(l) {
  95. * letters.push(l);
  96. * throttler.queue(deliver);
  97. * }
  98. */
  99. export class Throttler {
  100. constructor() {
  101. this.activePromise = null;
  102. this.queuedPromise = null;
  103. this.queuedPromiseFactory = null;
  104. }
  105. queue(promiseFactory) {
  106. if (this.activePromise) {
  107. this.queuedPromiseFactory = promiseFactory;
  108. if (!this.queuedPromise) {
  109. const onComplete = () => {
  110. this.queuedPromise = null;
  111. const result = this.queue(this.queuedPromiseFactory);
  112. this.queuedPromiseFactory = null;
  113. return result;
  114. };
  115. this.queuedPromise = new Promise(resolve => {
  116. this.activePromise.then(onComplete, onComplete).then(resolve);
  117. });
  118. }
  119. return new Promise((resolve, reject) => {
  120. this.queuedPromise.then(resolve, reject);
  121. });
  122. }
  123. this.activePromise = promiseFactory();
  124. return new Promise((resolve, reject) => {
  125. this.activePromise.then((result) => {
  126. this.activePromise = null;
  127. resolve(result);
  128. }, (err) => {
  129. this.activePromise = null;
  130. reject(err);
  131. });
  132. });
  133. }
  134. }
  135. const timeoutDeferred = (timeout, fn) => {
  136. let scheduled = true;
  137. const handle = setTimeout(() => {
  138. scheduled = false;
  139. fn();
  140. }, timeout);
  141. return {
  142. isTriggered: () => scheduled,
  143. dispose: () => {
  144. clearTimeout(handle);
  145. scheduled = false;
  146. },
  147. };
  148. };
  149. const microtaskDeferred = (fn) => {
  150. let scheduled = true;
  151. queueMicrotask(() => {
  152. if (scheduled) {
  153. scheduled = false;
  154. fn();
  155. }
  156. });
  157. return {
  158. isTriggered: () => scheduled,
  159. dispose: () => { scheduled = false; },
  160. };
  161. };
  162. /**
  163. * A helper to delay (debounce) execution of a task that is being requested often.
  164. *
  165. * Following the throttler, now imagine the mail man wants to optimize the number of
  166. * trips proactively. The trip itself can be long, so he decides not to make the trip
  167. * as soon as a letter is submitted. Instead he waits a while, in case more
  168. * letters are submitted. After said waiting period, if no letters were submitted, he
  169. * decides to make the trip. Imagine that N more letters were submitted after the first
  170. * one, all within a short period of time between each other. Even though N+1
  171. * submissions occurred, only 1 delivery was made.
  172. *
  173. * The delayer offers this behavior via the trigger() method, into which both the task
  174. * to be executed and the waiting period (delay) must be passed in as arguments. Following
  175. * the example:
  176. *
  177. * const delayer = new Delayer(WAITING_PERIOD);
  178. * const letters = [];
  179. *
  180. * function letterReceived(l) {
  181. * letters.push(l);
  182. * delayer.trigger(() => { return makeTheTrip(); });
  183. * }
  184. */
  185. export class Delayer {
  186. constructor(defaultDelay) {
  187. this.defaultDelay = defaultDelay;
  188. this.deferred = null;
  189. this.completionPromise = null;
  190. this.doResolve = null;
  191. this.doReject = null;
  192. this.task = null;
  193. }
  194. trigger(task, delay = this.defaultDelay) {
  195. this.task = task;
  196. this.cancelTimeout();
  197. if (!this.completionPromise) {
  198. this.completionPromise = new Promise((resolve, reject) => {
  199. this.doResolve = resolve;
  200. this.doReject = reject;
  201. }).then(() => {
  202. this.completionPromise = null;
  203. this.doResolve = null;
  204. if (this.task) {
  205. const task = this.task;
  206. this.task = null;
  207. return task();
  208. }
  209. return undefined;
  210. });
  211. }
  212. const fn = () => {
  213. var _a;
  214. this.deferred = null;
  215. (_a = this.doResolve) === null || _a === void 0 ? void 0 : _a.call(this, null);
  216. };
  217. this.deferred = delay === MicrotaskDelay ? microtaskDeferred(fn) : timeoutDeferred(delay, fn);
  218. return this.completionPromise;
  219. }
  220. isTriggered() {
  221. var _a;
  222. return !!((_a = this.deferred) === null || _a === void 0 ? void 0 : _a.isTriggered());
  223. }
  224. cancel() {
  225. var _a;
  226. this.cancelTimeout();
  227. if (this.completionPromise) {
  228. (_a = this.doReject) === null || _a === void 0 ? void 0 : _a.call(this, new CancellationError());
  229. this.completionPromise = null;
  230. }
  231. }
  232. cancelTimeout() {
  233. var _a;
  234. (_a = this.deferred) === null || _a === void 0 ? void 0 : _a.dispose();
  235. this.deferred = null;
  236. }
  237. dispose() {
  238. this.cancel();
  239. }
  240. }
  241. /**
  242. * A helper to delay execution of a task that is being requested often, while
  243. * preventing accumulation of consecutive executions, while the task runs.
  244. *
  245. * The mail man is clever and waits for a certain amount of time, before going
  246. * out to deliver letters. While the mail man is going out, more letters arrive
  247. * and can only be delivered once he is back. Once he is back the mail man will
  248. * do one more trip to deliver the letters that have accumulated while he was out.
  249. */
  250. export class ThrottledDelayer {
  251. constructor(defaultDelay) {
  252. this.delayer = new Delayer(defaultDelay);
  253. this.throttler = new Throttler();
  254. }
  255. trigger(promiseFactory, delay) {
  256. return this.delayer.trigger(() => this.throttler.queue(promiseFactory), delay);
  257. }
  258. cancel() {
  259. this.delayer.cancel();
  260. }
  261. dispose() {
  262. this.delayer.dispose();
  263. }
  264. }
  265. export function timeout(millis, token) {
  266. if (!token) {
  267. return createCancelablePromise(token => timeout(millis, token));
  268. }
  269. return new Promise((resolve, reject) => {
  270. const handle = setTimeout(() => {
  271. disposable.dispose();
  272. resolve();
  273. }, millis);
  274. const disposable = token.onCancellationRequested(() => {
  275. clearTimeout(handle);
  276. disposable.dispose();
  277. reject(new CancellationError());
  278. });
  279. });
  280. }
  281. export function disposableTimeout(handler, timeout = 0) {
  282. const timer = setTimeout(handler, timeout);
  283. return toDisposable(() => clearTimeout(timer));
  284. }
  285. export function first(promiseFactories, shouldStop = t => !!t, defaultValue = null) {
  286. let index = 0;
  287. const len = promiseFactories.length;
  288. const loop = () => {
  289. if (index >= len) {
  290. return Promise.resolve(defaultValue);
  291. }
  292. const factory = promiseFactories[index++];
  293. const promise = Promise.resolve(factory());
  294. return promise.then(result => {
  295. if (shouldStop(result)) {
  296. return Promise.resolve(result);
  297. }
  298. return loop();
  299. });
  300. };
  301. return loop();
  302. }
  303. export class TimeoutTimer {
  304. constructor(runner, timeout) {
  305. this._token = -1;
  306. if (typeof runner === 'function' && typeof timeout === 'number') {
  307. this.setIfNotSet(runner, timeout);
  308. }
  309. }
  310. dispose() {
  311. this.cancel();
  312. }
  313. cancel() {
  314. if (this._token !== -1) {
  315. clearTimeout(this._token);
  316. this._token = -1;
  317. }
  318. }
  319. cancelAndSet(runner, timeout) {
  320. this.cancel();
  321. this._token = setTimeout(() => {
  322. this._token = -1;
  323. runner();
  324. }, timeout);
  325. }
  326. setIfNotSet(runner, timeout) {
  327. if (this._token !== -1) {
  328. // timer is already set
  329. return;
  330. }
  331. this._token = setTimeout(() => {
  332. this._token = -1;
  333. runner();
  334. }, timeout);
  335. }
  336. }
  337. export class IntervalTimer {
  338. constructor() {
  339. this._token = -1;
  340. }
  341. dispose() {
  342. this.cancel();
  343. }
  344. cancel() {
  345. if (this._token !== -1) {
  346. clearInterval(this._token);
  347. this._token = -1;
  348. }
  349. }
  350. cancelAndSet(runner, interval) {
  351. this.cancel();
  352. this._token = setInterval(() => {
  353. runner();
  354. }, interval);
  355. }
  356. }
  357. export class RunOnceScheduler {
  358. constructor(runner, delay) {
  359. this.timeoutToken = -1;
  360. this.runner = runner;
  361. this.timeout = delay;
  362. this.timeoutHandler = this.onTimeout.bind(this);
  363. }
  364. /**
  365. * Dispose RunOnceScheduler
  366. */
  367. dispose() {
  368. this.cancel();
  369. this.runner = null;
  370. }
  371. /**
  372. * Cancel current scheduled runner (if any).
  373. */
  374. cancel() {
  375. if (this.isScheduled()) {
  376. clearTimeout(this.timeoutToken);
  377. this.timeoutToken = -1;
  378. }
  379. }
  380. /**
  381. * Cancel previous runner (if any) & schedule a new runner.
  382. */
  383. schedule(delay = this.timeout) {
  384. this.cancel();
  385. this.timeoutToken = setTimeout(this.timeoutHandler, delay);
  386. }
  387. get delay() {
  388. return this.timeout;
  389. }
  390. set delay(value) {
  391. this.timeout = value;
  392. }
  393. /**
  394. * Returns true if scheduled.
  395. */
  396. isScheduled() {
  397. return this.timeoutToken !== -1;
  398. }
  399. onTimeout() {
  400. this.timeoutToken = -1;
  401. if (this.runner) {
  402. this.doRun();
  403. }
  404. }
  405. doRun() {
  406. var _a;
  407. (_a = this.runner) === null || _a === void 0 ? void 0 : _a.call(this);
  408. }
  409. }
  410. /**
  411. * Execute the callback the next time the browser is idle, returning an
  412. * {@link IDisposable} that will cancel the callback when disposed. This wraps
  413. * [requestIdleCallback] so it will fallback to [setTimeout] if the environment
  414. * doesn't support it.
  415. *
  416. * @param callback The callback to run when idle, this includes an
  417. * [IdleDeadline] that provides the time alloted for the idle callback by the
  418. * browser. Not respecting this deadline will result in a degraded user
  419. * experience.
  420. * @param timeout A timeout at which point to queue no longer wait for an idle
  421. * callback but queue it on the regular event loop (like setTimeout). Typically
  422. * this should not be used.
  423. *
  424. * [IdleDeadline]: https://developer.mozilla.org/en-US/docs/Web/API/IdleDeadline
  425. * [requestIdleCallback]: https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback
  426. * [setTimeout]: https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout
  427. */
  428. export let runWhenIdle;
  429. (function () {
  430. if (typeof requestIdleCallback !== 'function' || typeof cancelIdleCallback !== 'function') {
  431. runWhenIdle = (runner) => {
  432. setTimeout0(() => {
  433. if (disposed) {
  434. return;
  435. }
  436. const end = Date.now() + 15; // one frame at 64fps
  437. runner(Object.freeze({
  438. didTimeout: true,
  439. timeRemaining() {
  440. return Math.max(0, end - Date.now());
  441. }
  442. }));
  443. });
  444. let disposed = false;
  445. return {
  446. dispose() {
  447. if (disposed) {
  448. return;
  449. }
  450. disposed = true;
  451. }
  452. };
  453. };
  454. }
  455. else {
  456. runWhenIdle = (runner, timeout) => {
  457. const handle = requestIdleCallback(runner, typeof timeout === 'number' ? { timeout } : undefined);
  458. let disposed = false;
  459. return {
  460. dispose() {
  461. if (disposed) {
  462. return;
  463. }
  464. disposed = true;
  465. cancelIdleCallback(handle);
  466. }
  467. };
  468. };
  469. }
  470. })();
  471. /**
  472. * An implementation of the "idle-until-urgent"-strategy as introduced
  473. * here: https://philipwalton.com/articles/idle-until-urgent/
  474. */
  475. export class IdleValue {
  476. constructor(executor) {
  477. this._didRun = false;
  478. this._executor = () => {
  479. try {
  480. this._value = executor();
  481. }
  482. catch (err) {
  483. this._error = err;
  484. }
  485. finally {
  486. this._didRun = true;
  487. }
  488. };
  489. this._handle = runWhenIdle(() => this._executor());
  490. }
  491. dispose() {
  492. this._handle.dispose();
  493. }
  494. get value() {
  495. if (!this._didRun) {
  496. this._handle.dispose();
  497. this._executor();
  498. }
  499. if (this._error) {
  500. throw this._error;
  501. }
  502. return this._value;
  503. }
  504. get isInitialized() {
  505. return this._didRun;
  506. }
  507. }
  508. /**
  509. * Creates a promise whose resolution or rejection can be controlled imperatively.
  510. */
  511. export class DeferredPromise {
  512. get isRejected() {
  513. return this.rejected;
  514. }
  515. get isSettled() {
  516. return this.rejected || this.resolved;
  517. }
  518. constructor() {
  519. this.rejected = false;
  520. this.resolved = false;
  521. this.p = new Promise((c, e) => {
  522. this.completeCallback = c;
  523. this.errorCallback = e;
  524. });
  525. }
  526. complete(value) {
  527. return new Promise(resolve => {
  528. this.completeCallback(value);
  529. this.resolved = true;
  530. resolve();
  531. });
  532. }
  533. cancel() {
  534. new Promise(resolve => {
  535. this.errorCallback(new CancellationError());
  536. this.rejected = true;
  537. resolve();
  538. });
  539. }
  540. }
  541. //#endregion
  542. //#region Promises
  543. export var Promises;
  544. (function (Promises) {
  545. /**
  546. * A drop-in replacement for `Promise.all` with the only difference
  547. * that the method awaits every promise to either fulfill or reject.
  548. *
  549. * Similar to `Promise.all`, only the first error will be returned
  550. * if any.
  551. */
  552. function settled(promises) {
  553. return __awaiter(this, void 0, void 0, function* () {
  554. let firstError = undefined;
  555. const result = yield Promise.all(promises.map(promise => promise.then(value => value, error => {
  556. if (!firstError) {
  557. firstError = error;
  558. }
  559. return undefined; // do not rethrow so that other promises can settle
  560. })));
  561. if (typeof firstError !== 'undefined') {
  562. throw firstError;
  563. }
  564. return result; // cast is needed and protected by the `throw` above
  565. });
  566. }
  567. Promises.settled = settled;
  568. /**
  569. * A helper to create a new `Promise<T>` with a body that is a promise
  570. * itself. By default, an error that raises from the async body will
  571. * end up as a unhandled rejection, so this utility properly awaits the
  572. * body and rejects the promise as a normal promise does without async
  573. * body.
  574. *
  575. * This method should only be used in rare cases where otherwise `async`
  576. * cannot be used (e.g. when callbacks are involved that require this).
  577. */
  578. function withAsyncBody(bodyFn) {
  579. // eslint-disable-next-line no-async-promise-executor
  580. return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
  581. try {
  582. yield bodyFn(resolve, reject);
  583. }
  584. catch (error) {
  585. reject(error);
  586. }
  587. }));
  588. }
  589. Promises.withAsyncBody = withAsyncBody;
  590. })(Promises || (Promises = {}));
  591. /**
  592. * A rich implementation for an `AsyncIterable<T>`.
  593. */
  594. export class AsyncIterableObject {
  595. static fromArray(items) {
  596. return new AsyncIterableObject((writer) => {
  597. writer.emitMany(items);
  598. });
  599. }
  600. static fromPromise(promise) {
  601. return new AsyncIterableObject((emitter) => __awaiter(this, void 0, void 0, function* () {
  602. emitter.emitMany(yield promise);
  603. }));
  604. }
  605. static fromPromises(promises) {
  606. return new AsyncIterableObject((emitter) => __awaiter(this, void 0, void 0, function* () {
  607. yield Promise.all(promises.map((p) => __awaiter(this, void 0, void 0, function* () { return emitter.emitOne(yield p); })));
  608. }));
  609. }
  610. static merge(iterables) {
  611. return new AsyncIterableObject((emitter) => __awaiter(this, void 0, void 0, function* () {
  612. yield Promise.all(iterables.map((iterable) => { var _a, iterable_1, iterable_1_1; return __awaiter(this, void 0, void 0, function* () {
  613. var _b, e_1, _c, _d;
  614. try {
  615. for (_a = true, iterable_1 = __asyncValues(iterable); iterable_1_1 = yield iterable_1.next(), _b = iterable_1_1.done, !_b;) {
  616. _d = iterable_1_1.value;
  617. _a = false;
  618. try {
  619. const item = _d;
  620. emitter.emitOne(item);
  621. }
  622. finally {
  623. _a = true;
  624. }
  625. }
  626. }
  627. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  628. finally {
  629. try {
  630. if (!_a && !_b && (_c = iterable_1.return)) yield _c.call(iterable_1);
  631. }
  632. finally { if (e_1) throw e_1.error; }
  633. }
  634. }); }));
  635. }));
  636. }
  637. constructor(executor) {
  638. this._state = 0 /* AsyncIterableSourceState.Initial */;
  639. this._results = [];
  640. this._error = null;
  641. this._onStateChanged = new Emitter();
  642. queueMicrotask(() => __awaiter(this, void 0, void 0, function* () {
  643. const writer = {
  644. emitOne: (item) => this.emitOne(item),
  645. emitMany: (items) => this.emitMany(items),
  646. reject: (error) => this.reject(error)
  647. };
  648. try {
  649. yield Promise.resolve(executor(writer));
  650. this.resolve();
  651. }
  652. catch (err) {
  653. this.reject(err);
  654. }
  655. finally {
  656. writer.emitOne = undefined;
  657. writer.emitMany = undefined;
  658. writer.reject = undefined;
  659. }
  660. }));
  661. }
  662. [Symbol.asyncIterator]() {
  663. let i = 0;
  664. return {
  665. next: () => __awaiter(this, void 0, void 0, function* () {
  666. do {
  667. if (this._state === 2 /* AsyncIterableSourceState.DoneError */) {
  668. throw this._error;
  669. }
  670. if (i < this._results.length) {
  671. return { done: false, value: this._results[i++] };
  672. }
  673. if (this._state === 1 /* AsyncIterableSourceState.DoneOK */) {
  674. return { done: true, value: undefined };
  675. }
  676. yield Event.toPromise(this._onStateChanged.event);
  677. } while (true);
  678. })
  679. };
  680. }
  681. static map(iterable, mapFn) {
  682. return new AsyncIterableObject((emitter) => __awaiter(this, void 0, void 0, function* () {
  683. var _a, e_2, _b, _c;
  684. try {
  685. for (var _d = true, iterable_2 = __asyncValues(iterable), iterable_2_1; iterable_2_1 = yield iterable_2.next(), _a = iterable_2_1.done, !_a;) {
  686. _c = iterable_2_1.value;
  687. _d = false;
  688. try {
  689. const item = _c;
  690. emitter.emitOne(mapFn(item));
  691. }
  692. finally {
  693. _d = true;
  694. }
  695. }
  696. }
  697. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  698. finally {
  699. try {
  700. if (!_d && !_a && (_b = iterable_2.return)) yield _b.call(iterable_2);
  701. }
  702. finally { if (e_2) throw e_2.error; }
  703. }
  704. }));
  705. }
  706. map(mapFn) {
  707. return AsyncIterableObject.map(this, mapFn);
  708. }
  709. static filter(iterable, filterFn) {
  710. return new AsyncIterableObject((emitter) => __awaiter(this, void 0, void 0, function* () {
  711. var _a, e_3, _b, _c;
  712. try {
  713. for (var _d = true, iterable_3 = __asyncValues(iterable), iterable_3_1; iterable_3_1 = yield iterable_3.next(), _a = iterable_3_1.done, !_a;) {
  714. _c = iterable_3_1.value;
  715. _d = false;
  716. try {
  717. const item = _c;
  718. if (filterFn(item)) {
  719. emitter.emitOne(item);
  720. }
  721. }
  722. finally {
  723. _d = true;
  724. }
  725. }
  726. }
  727. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  728. finally {
  729. try {
  730. if (!_d && !_a && (_b = iterable_3.return)) yield _b.call(iterable_3);
  731. }
  732. finally { if (e_3) throw e_3.error; }
  733. }
  734. }));
  735. }
  736. filter(filterFn) {
  737. return AsyncIterableObject.filter(this, filterFn);
  738. }
  739. static coalesce(iterable) {
  740. return AsyncIterableObject.filter(iterable, item => !!item);
  741. }
  742. coalesce() {
  743. return AsyncIterableObject.coalesce(this);
  744. }
  745. static toPromise(iterable) {
  746. var _a, iterable_4, iterable_4_1;
  747. var _b, e_4, _c, _d;
  748. return __awaiter(this, void 0, void 0, function* () {
  749. const result = [];
  750. try {
  751. for (_a = true, iterable_4 = __asyncValues(iterable); iterable_4_1 = yield iterable_4.next(), _b = iterable_4_1.done, !_b;) {
  752. _d = iterable_4_1.value;
  753. _a = false;
  754. try {
  755. const item = _d;
  756. result.push(item);
  757. }
  758. finally {
  759. _a = true;
  760. }
  761. }
  762. }
  763. catch (e_4_1) { e_4 = { error: e_4_1 }; }
  764. finally {
  765. try {
  766. if (!_a && !_b && (_c = iterable_4.return)) yield _c.call(iterable_4);
  767. }
  768. finally { if (e_4) throw e_4.error; }
  769. }
  770. return result;
  771. });
  772. }
  773. toPromise() {
  774. return AsyncIterableObject.toPromise(this);
  775. }
  776. /**
  777. * The value will be appended at the end.
  778. *
  779. * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.
  780. */
  781. emitOne(value) {
  782. if (this._state !== 0 /* AsyncIterableSourceState.Initial */) {
  783. return;
  784. }
  785. // it is important to add new values at the end,
  786. // as we may have iterators already running on the array
  787. this._results.push(value);
  788. this._onStateChanged.fire();
  789. }
  790. /**
  791. * The values will be appended at the end.
  792. *
  793. * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.
  794. */
  795. emitMany(values) {
  796. if (this._state !== 0 /* AsyncIterableSourceState.Initial */) {
  797. return;
  798. }
  799. // it is important to add new values at the end,
  800. // as we may have iterators already running on the array
  801. this._results = this._results.concat(values);
  802. this._onStateChanged.fire();
  803. }
  804. /**
  805. * Calling `resolve()` will mark the result array as complete.
  806. *
  807. * **NOTE** `resolve()` must be called, otherwise all consumers of this iterable will hang indefinitely, similar to a non-resolved promise.
  808. * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.
  809. */
  810. resolve() {
  811. if (this._state !== 0 /* AsyncIterableSourceState.Initial */) {
  812. return;
  813. }
  814. this._state = 1 /* AsyncIterableSourceState.DoneOK */;
  815. this._onStateChanged.fire();
  816. }
  817. /**
  818. * Writing an error will permanently invalidate this iterable.
  819. * The current users will receive an error thrown, as will all future users.
  820. *
  821. * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.
  822. */
  823. reject(error) {
  824. if (this._state !== 0 /* AsyncIterableSourceState.Initial */) {
  825. return;
  826. }
  827. this._state = 2 /* AsyncIterableSourceState.DoneError */;
  828. this._error = error;
  829. this._onStateChanged.fire();
  830. }
  831. }
  832. AsyncIterableObject.EMPTY = AsyncIterableObject.fromArray([]);
  833. export class CancelableAsyncIterableObject extends AsyncIterableObject {
  834. constructor(_source, executor) {
  835. super(executor);
  836. this._source = _source;
  837. }
  838. cancel() {
  839. this._source.cancel();
  840. }
  841. }
  842. export function createCancelableAsyncIterable(callback) {
  843. const source = new CancellationTokenSource();
  844. const innerIterable = callback(source.token);
  845. return new CancelableAsyncIterableObject(source, (emitter) => __awaiter(this, void 0, void 0, function* () {
  846. var _a, e_5, _b, _c;
  847. const subscription = source.token.onCancellationRequested(() => {
  848. subscription.dispose();
  849. source.dispose();
  850. emitter.reject(new CancellationError());
  851. });
  852. try {
  853. try {
  854. for (var _d = true, innerIterable_1 = __asyncValues(innerIterable), innerIterable_1_1; innerIterable_1_1 = yield innerIterable_1.next(), _a = innerIterable_1_1.done, !_a;) {
  855. _c = innerIterable_1_1.value;
  856. _d = false;
  857. try {
  858. const item = _c;
  859. if (source.token.isCancellationRequested) {
  860. // canceled in the meantime
  861. return;
  862. }
  863. emitter.emitOne(item);
  864. }
  865. finally {
  866. _d = true;
  867. }
  868. }
  869. }
  870. catch (e_5_1) { e_5 = { error: e_5_1 }; }
  871. finally {
  872. try {
  873. if (!_d && !_a && (_b = innerIterable_1.return)) yield _b.call(innerIterable_1);
  874. }
  875. finally { if (e_5) throw e_5.error; }
  876. }
  877. subscription.dispose();
  878. source.dispose();
  879. }
  880. catch (err) {
  881. subscription.dispose();
  882. source.dispose();
  883. emitter.reject(err);
  884. }
  885. }));
  886. }
  887. //#endregion