/********************************************************************************
 * Copyright (C) 2017 TypeFox and others.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v. 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0.
 *
 * This Source Code may also be made available under the following Secondary
 * Licenses when the conditions for such availability set forth in the Eclipse
 * Public License v. 2.0 are satisfied: GNU General Public License, version 2
 * with the GNU Classpath Exception which is available at
 * https://www.gnu.org/software/classpath/license.html.
 *
 * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
 ********************************************************************************/ import { Disposable } from './disposable' ; import { Event } from './event' ; import { CancellationToken , CancellationError , cancelled } from './cancellation' ; /**
 * Simple implementation of the deferred pattern.
 * An object that exposes a promise and functions to resolve and reject it.
 */ export class Deferred < T = void > { state : 'resolved' | 'rejected' | 'unresolved' = 'unresolved' ; resolve : ( value : T ) => void ; reject : ( err ? : any ) => void ; promise = new Promise < T > ( ( resolve , reject ) => { this . resolve = result => { resolve ( result ) ; if ( this . state === 'unresolved' ) { this . state = 'resolved' ; } } ; this . reject = err => { reject ( err ) ; if ( this . state === 'unresolved' ) { this . state = 'rejected' ; } } ; } ) ; } returns throws export function timeout ( ms , token = CancellationToken . None ) { const deferred = new Deferred < void > ( ) ; const handle = setTimeout ( ( ) => deferred . resolve ( ) , ms ) ; token . onCancellationRequested ( ( ) => { clearTimeout ( handle ) ; deferred . reject ( cancelled ( ) ) ; } ) ; return deferred . promise ; } export async function retry < T > ( task , retryDelay , retries ) { let lastError ; for ( let i = 0 ; i < retries ; i ++ ) { try { return await task ( ) ; } catch ( error ) { lastError = error ; await timeout ( retryDelay ) ; } } throw lastError ; } param ms returns export function delay < T > ( ms ) { return value => new Promise ( ( resolve , reject ) => { setTimeout ( ( ) => resolve ( value ) , ms ) ; } ) ; } param ms export async function wait ( ms ) { await delay ( ms ) ( undefined ) ; } export function waitForEvent < T > ( event , ms , thisArg ? , disposables ? ) { return new Promise < T > ( ( resolve , reject ) => { const registration = setTimeout ( ( ) => { listener . dispose ( ) ; reject ( new CancellationError ( ) ) ; } , ms ) ; const listener = event ( ( evt ) => { clearTimeout ( registration ) ; listener . dispose ( ) ; resolve ( evt ) ; } , thisArg , disposables ) ; } ) ; }