microsoft/vscode-react-native

Public

mirrored from https://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
e4ac653e109fbed056449d4ec6ef8b37b6dce8c0

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/common/node/promise.ts

52lines · modeblame

2f10b3adunknown10 years ago1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT license. See LICENSE file in the project root for details.
3
a116786bJimmy Thomson10 years ago4import * as Q from "q";
5
2f10b3adunknown10 years ago6/**
7* Utilities for working with promises.
8*/
34ec0375Daniel10 years ago9export class PromiseUtil {
2f10b3adunknown10 years ago10/**
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*/
a116786bJimmy Thomson10 years ago21public retryAsync<T>(operation: () => Q.Promise<T>, condition: (result: T) => boolean | Q.Promise<boolean>, maxRetries: number, delay: number, failure: string): Q.Promise<T> {
2f10b3adunknown10 years ago22return this.retryAsyncIteration(operation, condition, maxRetries, 0, delay, failure);
23}
24
bc6696cbdigeff10 years ago25public reduce<T>(sources: T[]|Q.Promise<T[]>, generateAsyncOperation: (value: T) => Q.Promise<void>): Q.Promise<void> {
26const promisedSources = <Q.Promise<T[]>>Q(sources);
27return promisedSources.then(resolvedSources => {
28return resolvedSources.reduce((previousReduction: Q.Promise<void>, newSource: T) => {
29return previousReduction.then(() => {
30return generateAsyncOperation(newSource);
31});
32}, Q<void>(void 0));
33});
34}
35
a116786bJimmy Thomson10 years ago36private retryAsyncIteration<T>(operation: () => Q.Promise<T>, condition: (result: T) => boolean | Q.Promise<boolean>, maxRetries: number, iteration: number, delay: number, failure: string): Q.Promise<T> {
2f10b3adunknown10 years ago37return operation()
38.then(result => {
39return Q(result).then(condition).then((conditionResult => {
40if (conditionResult) {
41return result;
42}
43
44if (iteration < maxRetries) {
45return Q.delay(delay).then(() => this.retryAsyncIteration(operation, condition, maxRetries, iteration + 1, delay, failure));
46}
47
48throw new Error(failure);
49}));
50});
51}
52}