microsoft/vscode-react-native
Publicmirrored from https://github.com/microsoft/vscode-react-nativeAvailable
src/common/node/promise.ts
52lines · modeblame
2f10b3adunknown10 years ago | 1 | // 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 ago | 4 | import * as Q from "q"; |
| 5 | | |
2f10b3adunknown10 years ago | 6 | /** |
| 7 | * Utilities for working with promises. | |
| 8 | */ | |
34ec0375Daniel10 years ago | 9 | export class PromiseUtil { |
2f10b3adunknown10 years ago | 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 | */ | |
a116786bJimmy Thomson10 years ago | 21 | public retryAsync<T>(operation: () => Q.Promise<T>, condition: (result: T) => boolean | Q.Promise<boolean>, maxRetries: number, delay: number, failure: string): Q.Promise<T> { |
2f10b3adunknown10 years ago | 22 | return this.retryAsyncIteration(operation, condition, maxRetries, 0, delay, failure); |
| 23 | } | |
| 24 | | |
bc6696cbdigeff10 years ago | 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 | | |
a116786bJimmy Thomson10 years ago | 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> { |
2f10b3adunknown10 years ago | 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 | } |