microsoft/vscode-react-native

Public

mirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
2d2a33644976c159bb50bad9df3cb949f150a8ec

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

src/common/node/promise.ts

41lines · modecode

1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT license. See LICENSE file in the project root for details.
3
4import * as Q from "q";
5
6/**
7 * Utilities for working with promises.
8 */
9export class PromiseUtil {
10 /**
11 * Retries an operation a given number of times. For each retry, a condition is checked.
12 * If the condition is not satisfied after the maximum number of retries, and error is thrown.
13 * Otherwise, the result of the operation is returned once the condition is satisfied.
14 *
15 * @param operation - the function to execute.
16 * @param condition - the condition to check between iterations.
17 * @param maxRetries - the maximum number of retries.
18 * @param delay - time between iterations, in milliseconds.
19 * @param failure - error description.
20 */
21 public retryAsync<T>(operation: () => Q.Promise<T>, condition: (result: T) => boolean | Q.Promise<boolean>, maxRetries: number, delay: number, failure: string): Q.Promise<T> {
22 return this.retryAsyncIteration(operation, condition, maxRetries, 0, delay, failure);
23 }
24
25 private retryAsyncIteration<T>(operation: () => Q.Promise<T>, condition: (result: T) => boolean | Q.Promise<boolean>, maxRetries: number, iteration: number, delay: number, failure: string): Q.Promise<T> {
26 return operation()
27 .then(result => {
28 return Q(result).then(condition).then((conditionResult => {
29 if (conditionResult) {
30 return result;
31 }
32
33 if (iteration < maxRetries) {
34 return Q.delay(delay).then(() => this.retryAsyncIteration(operation, condition, maxRetries, iteration + 1, delay, failure));
35 }
36
37 throw new Error(failure);
38 }));
39 });
40 }
41}