microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
bb77358c8dc7ea46fae9d6aa601a11fde8eed0fd

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/common/node/promise.ts

52lines · 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 public reduce<T>(sources: T[]|Q.Promise<T[]>, generateAsyncOperation: (value: T) => Q.Promise<void>): Q.Promise<void> {
26 const promisedSources = <Q.Promise<T[]>>Q(sources);
27 return promisedSources.then(resolvedSources => {
28 return resolvedSources.reduce((previousReduction: Q.Promise<void>, newSource: T) => {
29 return previousReduction.then(() => {
30 return generateAsyncOperation(newSource);
31 });
32 }, Q<void>(void 0));
33 });
34 }
35
36 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> {
37 return operation()
38 .then(result => {
39 return Q(result).then(condition).then((conditionResult => {
40 if (conditionResult) {
41 return result;
42 }
43
44 if (iteration < maxRetries) {
45 return Q.delay(delay).then(() => this.retryAsyncIteration(operation, condition, maxRetries, iteration + 1, delay, failure));
46 }
47
48 throw new Error(failure);
49 }));
50 });
51 }
52}