async.ts 16.8 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
J
Joao Moreno 已提交
5

E
Erich Gamma 已提交
6 7
'use strict';

J
Johannes Rieken 已提交
8
import * as errors from 'vs/base/common/errors';
J
Joao Moreno 已提交
9 10
import { Promise, TPromise, ValueCallback, ErrorCallback, ProgressCallback } from 'vs/base/common/winjs.base';
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
11
import { Disposable, IDisposable } from 'vs/base/common/lifecycle';
M
Matt Bierner 已提交
12
import { Event, Emitter } from 'vs/base/common/event';
13
import URI from 'vs/base/common/uri';
14

15
export function isThenable<T>(obj: any): obj is Thenable<T> {
16 17 18
	return obj && typeof (<Thenable<any>>obj).then === 'function';
}

19 20 21 22 23 24 25 26
export function toThenable<T>(arg: T | Thenable<T>): Thenable<T> {
	if (isThenable(arg)) {
		return arg;
	} else {
		return TPromise.as(arg);
	}
}

27
export function asWinJsPromise<T>(callback: (token: CancellationToken) => T | TPromise<T> | Thenable<T>): TPromise<T> {
28
	let source = new CancellationTokenSource();
29
	return new TPromise<T>((resolve, reject, progress) => {
30
		let item = callback(source.token);
31
		if (item instanceof TPromise) {
32 33
			item.then(resolve, reject, progress);
		} else if (isThenable<T>(item)) {
34 35 36 37 38 39 40 41
			item.then(resolve, reject);
		} else {
			resolve(item);
		}
	}, () => {
		source.cancel();
	});
}
E
Erich Gamma 已提交
42

43 44 45
/**
 * Hook a cancellation token to a WinJS Promise
 */
46
export function wireCancellationToken<T>(token: CancellationToken, promise: TPromise<T>, resolveAsUndefinedWhenCancelled?: boolean): Thenable<T> {
47
	const subscription = token.onCancellationRequested(() => promise.cancel());
48
	if (resolveAsUndefinedWhenCancelled) {
49
		promise = promise.then<T>(undefined, err => {
50 51 52
			if (!errors.isPromiseCanceledError(err)) {
				return TPromise.wrapError(err);
			}
M
Matt Bierner 已提交
53
			return undefined;
54 55
		});
	}
56
	return always(promise, () => subscription.dispose());
57 58
}

E
Erich Gamma 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
export interface ITask<T> {
	(): T;
}

/**
 * A helper to prevent accumulation of sequential async tasks.
 *
 * Imagine a mail man with the sole task of delivering letters. As soon as
 * a letter submitted for delivery, he drives to the destination, delivers it
 * and returns to his base. Imagine that during the trip, N more letters were submitted.
 * When the mail man returns, he picks those N letters and delivers them all in a
 * single trip. Even though N+1 submissions occurred, only 2 deliveries were made.
 *
 * The throttler implements this via the queue() method, by providing it a task
 * factory. Following the example:
 *
B
Benjamin Pasero 已提交
75 76
 * 		const throttler = new Throttler();
 * 		const letters = [];
E
Erich Gamma 已提交
77
 *
J
Joao Moreno 已提交
78 79 80 81 82 83 84
 * 		function deliver() {
 * 			const lettersToDeliver = letters;
 * 			letters = [];
 * 			return makeTheTrip(lettersToDeliver);
 * 		}
 *
 * 		function onLetterReceived(l) {
E
Erich Gamma 已提交
85
 * 			letters.push(l);
J
Joao Moreno 已提交
86
 * 			throttler.queue(deliver);
E
Erich Gamma 已提交
87 88 89 90 91 92 93 94 95 96 97 98 99 100
 * 		}
 */
export class Throttler {

	private activePromise: Promise;
	private queuedPromise: Promise;
	private queuedPromiseFactory: ITask<Promise>;

	constructor() {
		this.activePromise = null;
		this.queuedPromise = null;
		this.queuedPromiseFactory = null;
	}

J
Joao Moreno 已提交
101
	queue<T>(promiseFactory: ITask<TPromise<T>>): TPromise<T> {
E
Erich Gamma 已提交
102 103 104 105
		if (this.activePromise) {
			this.queuedPromiseFactory = promiseFactory;

			if (!this.queuedPromise) {
J
Johannes Rieken 已提交
106
				const onComplete = () => {
E
Erich Gamma 已提交
107 108
					this.queuedPromise = null;

J
Johannes Rieken 已提交
109
					const result = this.queue(this.queuedPromiseFactory);
E
Erich Gamma 已提交
110 111 112 113 114
					this.queuedPromiseFactory = null;

					return result;
				};

115
				this.queuedPromise = new TPromise((c, e, p) => {
E
Erich Gamma 已提交
116 117 118 119 120 121
					this.activePromise.then(onComplete, onComplete, p).done(c);
				}, () => {
					this.activePromise.cancel();
				});
			}

122
			return new TPromise((c, e, p) => {
E
Erich Gamma 已提交
123 124 125 126 127 128 129 130
				this.queuedPromise.then(c, e, p);
			}, () => {
				// no-op
			});
		}

		this.activePromise = promiseFactory();

131
		return new TPromise((c, e, p) => {
E
Erich Gamma 已提交
132 133 134 135 136 137 138 139 140 141 142 143 144
			this.activePromise.done((result: any) => {
				this.activePromise = null;
				c(result);
			}, (err: any) => {
				this.activePromise = null;
				e(err);
			}, p);
		}, () => {
			this.activePromise.cancel();
		});
	}
}

145 146 147
// TODO@Joao: can the previous throttler be replaced with this?
export class SimpleThrottler {

148
	private current = TPromise.wrap<any>(null);
149 150 151 152 153 154

	queue<T>(promiseTask: ITask<TPromise<T>>): TPromise<T> {
		return this.current = this.current.then(() => promiseTask());
	}
}

E
Erich Gamma 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
/**
 * A helper to delay execution of a task that is being requested often.
 *
 * Following the throttler, now imagine the mail man wants to optimize the number of
 * trips proactively. The trip itself can be long, so the he decides not to make the trip
 * as soon as a letter is submitted. Instead he waits a while, in case more
 * letters are submitted. After said waiting period, if no letters were submitted, he
 * decides to make the trip. Imagine that N more letters were submitted after the first
 * one, all within a short period of time between each other. Even though N+1
 * submissions occurred, only 1 delivery was made.
 *
 * The delayer offers this behavior via the trigger() method, into which both the task
 * to be executed and the waiting period (delay) must be passed in as arguments. Following
 * the example:
 *
B
Benjamin Pasero 已提交
170 171
 * 		const delayer = new Delayer(WAITING_PERIOD);
 * 		const letters = [];
E
Erich Gamma 已提交
172 173 174 175 176 177 178 179 180 181 182
 *
 * 		function letterReceived(l) {
 * 			letters.push(l);
 * 			delayer.trigger(() => { return makeTheTrip(); });
 * 		}
 */
export class Delayer<T> {

	private timeout: number;
	private completionPromise: Promise;
	private onSuccess: ValueCallback;
183
	private task: ITask<T | TPromise<T>>;
E
Erich Gamma 已提交
184

J
Joao Moreno 已提交
185
	constructor(public defaultDelay: number) {
E
Erich Gamma 已提交
186 187 188 189 190 191
		this.timeout = null;
		this.completionPromise = null;
		this.onSuccess = null;
		this.task = null;
	}

192
	trigger(task: ITask<T | TPromise<T>>, delay: number = this.defaultDelay): TPromise<T> {
E
Erich Gamma 已提交
193 194 195 196
		this.task = task;
		this.cancelTimeout();

		if (!this.completionPromise) {
197
			this.completionPromise = new TPromise((c) => {
E
Erich Gamma 已提交
198 199 200 201 202 203
				this.onSuccess = c;
			}, () => {
				// no-op
			}).then(() => {
				this.completionPromise = null;
				this.onSuccess = null;
J
Joao Moreno 已提交
204
				const task = this.task;
E
Erich Gamma 已提交
205 206
				this.task = null;

J
Joao Moreno 已提交
207
				return task();
E
Erich Gamma 已提交
208 209 210 211 212 213 214 215 216 217 218
			});
		}

		this.timeout = setTimeout(() => {
			this.timeout = null;
			this.onSuccess(null);
		}, delay);

		return this.completionPromise;
	}

J
Joao Moreno 已提交
219
	isTriggered(): boolean {
E
Erich Gamma 已提交
220 221 222
		return this.timeout !== null;
	}

J
Joao Moreno 已提交
223
	cancel(): void {
E
Erich Gamma 已提交
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
		this.cancelTimeout();

		if (this.completionPromise) {
			this.completionPromise.cancel();
			this.completionPromise = null;
		}
	}

	private cancelTimeout(): void {
		if (this.timeout !== null) {
			clearTimeout(this.timeout);
			this.timeout = null;
		}
	}
}

/**
 * A helper to delay execution of a task that is being requested often, while
 * preventing accumulation of consecutive executions, while the task runs.
 *
 * Simply combine the two mail man strategies from the Throttler and Delayer
 * helpers, for an analogy.
 */
J
Joao Moreno 已提交
247
export class ThrottledDelayer<T> extends Delayer<TPromise<T>> {
E
Erich Gamma 已提交
248 249 250 251 252 253 254 255 256

	private throttler: Throttler;

	constructor(defaultDelay: number) {
		super(defaultDelay);

		this.throttler = new Throttler();
	}

257
	trigger(promiseFactory: ITask<TPromise<T>>, delay?: number): TPromise {
E
Erich Gamma 已提交
258 259 260 261
		return super.trigger(() => this.throttler.queue(promiseFactory), delay);
	}
}

J
Joao Moreno 已提交
262 263 264 265
/**
 * A barrier that is initially closed and then becomes opened permanently.
 */
export class Barrier {
E
Erich Gamma 已提交
266

J
Joao Moreno 已提交
267 268 269
	private _isOpen: boolean;
	private _promise: TPromise<boolean>;
	private _completePromise: (v: boolean) => void;
E
Erich Gamma 已提交
270 271

	constructor() {
J
Joao Moreno 已提交
272 273 274 275 276
		this._isOpen = false;
		this._promise = new TPromise<boolean>((c, e, p) => {
			this._completePromise = c;
		}, () => {
			console.warn('You should really not try to cancel this ready promise!');
E
Erich Gamma 已提交
277 278 279
		});
	}

J
Joao Moreno 已提交
280 281
	isOpen(): boolean {
		return this._isOpen;
E
Erich Gamma 已提交
282 283
	}

J
Joao Moreno 已提交
284 285 286
	open(): void {
		this._isOpen = true;
		this._completePromise(true);
E
Erich Gamma 已提交
287 288
	}

J
Joao Moreno 已提交
289 290
	wait(): TPromise<boolean> {
		return this._promise;
E
Erich Gamma 已提交
291 292 293 294 295 296 297
	}
}

export class ShallowCancelThenPromise<T> extends TPromise<T> {

	constructor(outer: TPromise<T>) {

J
Johannes Rieken 已提交
298
		let completeCallback: ValueCallback,
E
Erich Gamma 已提交
299 300 301 302
			errorCallback: ErrorCallback,
			progressCallback: ProgressCallback;

		super((c, e, p) => {
J
Joao Moreno 已提交
303
			completeCallback = c;
E
Erich Gamma 已提交
304 305 306 307 308 309 310 311 312 313 314 315
			errorCallback = e;
			progressCallback = p;
		}, () => {
			// cancel this promise but not the
			// outer promise
			errorCallback(errors.canceled());
		});

		outer.then(completeCallback, errorCallback, progressCallback);
	}
}

316 317 318 319 320 321 322
/**
 * Replacement for `WinJS.Promise.timeout`.
 */
export function timeout(n: number): Promise<void> {
	return new Promise(resolve => setTimeout(resolve, n));
}

E
Erich Gamma 已提交
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
/**
 * Returns a new promise that joins the provided promise. Upon completion of
 * the provided promise the provided function will always be called. This
 * method is comparable to a try-finally code block.
 * @param promise a promise
 * @param f a function that will be call in the success and error case.
 */
export function always<T>(promise: TPromise<T>, f: Function): TPromise<T> {
	return new TPromise<T>((c, e, p) => {
		promise.done((result) => {
			try {
				f(result);
			} catch (e1) {
				errors.onUnexpectedError(e1);
			}
			c(result);
		}, (err) => {
			try {
				f(err);
			} catch (e1) {
				errors.onUnexpectedError(e1);
			}
			e(err);
		}, (progress) => {
			p(progress);
		});
	}, () => {
		promise.cancel();
	});
}

/**
 * Runs the provided list of promise factories in sequential order. The returned
 * promise will complete to an array of results from each promise.
 */
358 359

export function sequence<T>(promiseFactories: ITask<Thenable<T>>[]): TPromise<T[]> {
J
Johannes Rieken 已提交
360
	const results: T[] = [];
E
Erich Gamma 已提交
361

J
Johannes Rieken 已提交
362
	// reverse since we start with last element using pop()
J
Joao Moreno 已提交
363
	promiseFactories = promiseFactories.reverse();
E
Erich Gamma 已提交
364

365
	function next(): Thenable<any> {
J
Joao Moreno 已提交
366 367
		if (promiseFactories.length) {
			return promiseFactories.pop()();
E
Erich Gamma 已提交
368 369 370 371 372
		}

		return null;
	}

373
	function thenHandler(result: any): Thenable<any> {
374
		if (result !== undefined && result !== null) {
E
Erich Gamma 已提交
375 376 377
			results.push(result);
		}

J
Johannes Rieken 已提交
378
		const n = next();
E
Erich Gamma 已提交
379 380 381 382 383 384 385
		if (n) {
			return n.then(thenHandler);
		}

		return TPromise.as(results);
	}

A
Alex Dima 已提交
386
	return TPromise.as(null).then(thenHandler);
E
Erich Gamma 已提交
387 388
}

J
Joao Moreno 已提交
389 390 391
export function first<T>(promiseFactories: ITask<TPromise<T>>[], shouldStop: (t: T) => boolean = t => !!t): TPromise<T> {
	promiseFactories = [...promiseFactories.reverse()];

B
Benjamin Pasero 已提交
392
	const loop: () => TPromise<T> = () => {
J
Joao Moreno 已提交
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
		if (promiseFactories.length === 0) {
			return TPromise.as(null);
		}

		const factory = promiseFactories.pop();
		const promise = factory();

		return promise.then(result => {
			if (shouldStop(result)) {
				return TPromise.as(result);
			}

			return loop();
		});
	};

	return loop();
}

E
Erich Gamma 已提交
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
interface ILimitedTaskFactory {
	factory: ITask<Promise>;
	c: ValueCallback;
	e: ErrorCallback;
	p: ProgressCallback;
}

/**
 * A helper to queue N promises and run them all with a max degree of parallelism. The helper
 * ensures that at any time no more than M promises are running at the same time.
 */
export class Limiter<T> {
	private runningPromises: number;
	private maxDegreeOfParalellism: number;
	private outstandingPromises: ILimitedTaskFactory[];
M
Matt Bierner 已提交
427
	private readonly _onFinished: Emitter<void>;
E
Erich Gamma 已提交
428 429 430 431 432

	constructor(maxDegreeOfParalellism: number) {
		this.maxDegreeOfParalellism = maxDegreeOfParalellism;
		this.outstandingPromises = [];
		this.runningPromises = 0;
433 434 435 436 437
		this._onFinished = new Emitter<void>();
	}

	public get onFinished(): Event<void> {
		return this._onFinished.event;
E
Erich Gamma 已提交
438 439
	}

440 441 442 443
	public get size(): number {
		return this.runningPromises + this.outstandingPromises.length;
	}

J
Joao Moreno 已提交
444 445
	queue(promiseFactory: ITask<Promise>): Promise;
	queue(promiseFactory: ITask<TPromise<T>>): TPromise<T> {
E
Erich Gamma 已提交
446 447 448 449 450 451 452 453 454 455 456 457 458 459
		return new TPromise<T>((c, e, p) => {
			this.outstandingPromises.push({
				factory: promiseFactory,
				c: c,
				e: e,
				p: p
			});

			this.consume();
		});
	}

	private consume(): void {
		while (this.outstandingPromises.length && this.runningPromises < this.maxDegreeOfParalellism) {
J
Johannes Rieken 已提交
460
			const iLimitedTask = this.outstandingPromises.shift();
E
Erich Gamma 已提交
461 462
			this.runningPromises++;

J
Johannes Rieken 已提交
463
			const promise = iLimitedTask.factory();
E
Erich Gamma 已提交
464 465 466 467 468 469 470
			promise.done(iLimitedTask.c, iLimitedTask.e, iLimitedTask.p);
			promise.done(() => this.consumed(), () => this.consumed());
		}
	}

	private consumed(): void {
		this.runningPromises--;
471 472 473 474 475 476 477 478 479 480

		if (this.outstandingPromises.length > 0) {
			this.consume();
		} else {
			this._onFinished.fire();
		}
	}

	public dispose(): void {
		this._onFinished.dispose();
E
Erich Gamma 已提交
481 482 483
	}
}

B
Benjamin Pasero 已提交
484 485 486 487 488 489 490 491 492 493
/**
 * A queue is handles one promise at a time and guarantees that at any time only one promise is executing.
 */
export class Queue<T> extends Limiter<T> {

	constructor() {
		super(1);
	}
}

494 495 496 497
/**
 * A helper to organize queues per resource. The ResourceQueue makes sure to manage queues per resource
 * by disposing them once the queue is empty.
 */
B
Benjamin Pasero 已提交
498
export class ResourceQueue {
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
	private queues: { [path: string]: Queue<void> };

	constructor() {
		this.queues = Object.create(null);
	}

	public queueFor(resource: URI): Queue<void> {
		const key = resource.toString();
		if (!this.queues[key]) {
			const queue = new Queue<void>();
			queue.onFinished(() => {
				queue.dispose();
				delete this.queues[key];
			});

			this.queues[key] = queue;
		}

		return this.queues[key];
	}
}

521 522 523 524 525
export function setDisposableTimeout(handler: Function, timeout: number, ...args: any[]): IDisposable {
	const handle = setTimeout(handler, timeout, ...args);
	return { dispose() { clearTimeout(handle); } };
}

A
Alex Dima 已提交
526
export class TimeoutTimer extends Disposable {
A
Alex Dima 已提交
527
	private _token: number;
A
Alex Dima 已提交
528 529 530 531 532 533

	constructor() {
		super();
		this._token = -1;
	}

J
Joao Moreno 已提交
534
	dispose(): void {
A
Alex Dima 已提交
535 536 537 538
		this.cancel();
		super.dispose();
	}

J
Joao Moreno 已提交
539
	cancel(): void {
A
Alex Dima 已提交
540
		if (this._token !== -1) {
A
Alex Dima 已提交
541
			clearTimeout(this._token);
A
Alex Dima 已提交
542 543 544 545
			this._token = -1;
		}
	}

J
Johannes Rieken 已提交
546
	cancelAndSet(runner: () => void, timeout: number): void {
A
Alex Dima 已提交
547
		this.cancel();
A
Alex Dima 已提交
548
		this._token = setTimeout(() => {
A
Alex Dima 已提交
549 550 551 552 553
			this._token = -1;
			runner();
		}, timeout);
	}

J
Joao Moreno 已提交
554
	setIfNotSet(runner: () => void, timeout: number): void {
A
Alex Dima 已提交
555 556 557 558
		if (this._token !== -1) {
			// timer is already set
			return;
		}
A
Alex Dima 已提交
559
		this._token = setTimeout(() => {
A
Alex Dima 已提交
560 561 562 563 564 565 566
			this._token = -1;
			runner();
		}, timeout);
	}
}

export class IntervalTimer extends Disposable {
J
Joao Moreno 已提交
567

A
Alex Dima 已提交
568
	private _token: number;
A
Alex Dima 已提交
569 570 571 572 573 574

	constructor() {
		super();
		this._token = -1;
	}

J
Joao Moreno 已提交
575
	dispose(): void {
A
Alex Dima 已提交
576 577 578 579
		this.cancel();
		super.dispose();
	}

J
Joao Moreno 已提交
580
	cancel(): void {
A
Alex Dima 已提交
581
		if (this._token !== -1) {
A
Alex Dima 已提交
582
			clearInterval(this._token);
A
Alex Dima 已提交
583 584 585 586
			this._token = -1;
		}
	}

J
Johannes Rieken 已提交
587
	cancelAndSet(runner: () => void, interval: number): void {
A
Alex Dima 已提交
588
		this.cancel();
A
Alex Dima 已提交
589
		this._token = setInterval(() => {
A
Alex Dima 已提交
590 591 592 593 594
			runner();
		}, interval);
	}
}

E
Erich Gamma 已提交
595 596
export class RunOnceScheduler {

A
Alex Dima 已提交
597
	private timeoutToken: number;
E
Erich Gamma 已提交
598 599 600 601 602 603 604 605 606 607 608 609 610 611
	private runner: () => void;
	private timeout: number;
	private timeoutHandler: () => void;

	constructor(runner: () => void, timeout: number) {
		this.timeoutToken = -1;
		this.runner = runner;
		this.timeout = timeout;
		this.timeoutHandler = this.onTimeout.bind(this);
	}

	/**
	 * Dispose RunOnceScheduler
	 */
J
Joao Moreno 已提交
612
	dispose(): void {
E
Erich Gamma 已提交
613 614 615 616 617
		this.cancel();
		this.runner = null;
	}

	/**
618
	 * Cancel current scheduled runner (if any).
E
Erich Gamma 已提交
619
	 */
J
Joao Moreno 已提交
620
	cancel(): void {
I
isidor 已提交
621
		if (this.isScheduled()) {
A
Alex Dima 已提交
622
			clearTimeout(this.timeoutToken);
E
Erich Gamma 已提交
623 624 625 626 627 628 629
			this.timeoutToken = -1;
		}
	}

	/**
	 * Cancel previous runner (if any) & schedule a new runner.
	 */
J
Joao Moreno 已提交
630
	schedule(delay = this.timeout): void {
E
Erich Gamma 已提交
631
		this.cancel();
A
Alex Dima 已提交
632
		this.timeoutToken = setTimeout(this.timeoutHandler, delay);
E
Erich Gamma 已提交
633 634
	}

I
isidor 已提交
635 636 637
	/**
	 * Returns true if scheduled.
	 */
J
Joao Moreno 已提交
638
	isScheduled(): boolean {
I
isidor 已提交
639 640 641
		return this.timeoutToken !== -1;
	}

E
Erich Gamma 已提交
642 643 644 645 646 647 648 649 650 651 652
	private onTimeout() {
		this.timeoutToken = -1;
		if (this.runner) {
			this.runner();
		}
	}
}

export function nfcall(fn: Function, ...args: any[]): Promise;
export function nfcall<T>(fn: Function, ...args: any[]): TPromise<T>;
export function nfcall(fn: Function, ...args: any[]): any {
653
	return new TPromise((c, e) => fn(...args, (err: any, result: any) => err ? e(err) : c(result)), () => null);
E
Erich Gamma 已提交
654 655 656 657 658
}

export function ninvoke(thisArg: any, fn: Function, ...args: any[]): Promise;
export function ninvoke<T>(thisArg: any, fn: Function, ...args: any[]): TPromise<T>;
export function ninvoke(thisArg: any, fn: Function, ...args: any[]): any {
659
	return new TPromise((c, e) => fn.call(thisArg, ...args, (err: any, result: any) => err ? e(err) : c(result)), () => null);
660
}
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701

/**
 * An emitter that will ignore any events that occur during a specific code
 * execution triggered via throttle() until the promise has finished (either
 * successfully or with an error). Only after the promise has finished, the
 * last event that was fired during the operation will get emitted.
 *
 */
export class ThrottledEmitter<T> extends Emitter<T> {
	private suspended: boolean;

	private lastEvent: T;
	private hasLastEvent: boolean;

	public throttle<C>(promise: TPromise<C>): TPromise<C> {
		this.suspended = true;

		return always(promise, () => this.resume());
	}

	public fire(event?: T): any {
		if (this.suspended) {
			this.lastEvent = event;
			this.hasLastEvent = true;

			return;
		}

		return super.fire(event);
	}

	private resume(): void {
		this.suspended = false;

		if (this.hasLastEvent) {
			this.fire(this.lastEvent);
		}

		this.hasLastEvent = false;
		this.lastEvent = void 0;
	}
702
}