(
promises: Array<Promise<T>>, onProgress: OnProgressCallback,
startFraction?: number, endFraction?: number)
| 28 | * @param endFraction Optional fraction end. Default to 1. |
| 29 | */ |
| 30 | export function monitorPromisesProgress<T>( |
| 31 | promises: Array<Promise<T>>, onProgress: OnProgressCallback, |
| 32 | startFraction?: number, endFraction?: number) { |
| 33 | checkPromises(promises); |
| 34 | startFraction = startFraction == null ? 0 : startFraction; |
| 35 | endFraction = endFraction == null ? 1 : endFraction; |
| 36 | checkFraction(startFraction, endFraction); |
| 37 | let resolvedPromise = 0; |
| 38 | |
| 39 | const registerMonitor = (promise: Promise<T>) => { |
| 40 | promise.then(value => { |
| 41 | const fraction = startFraction + |
| 42 | ++resolvedPromise / promises.length * (endFraction - startFraction); |
| 43 | // pass fraction as parameter to callback function. |
| 44 | onProgress(fraction); |
| 45 | return value; |
| 46 | }); |
| 47 | return promise; |
| 48 | }; |
| 49 | |
| 50 | function checkPromises(promises: Array<Promise<T>>): void { |
| 51 | assert( |
| 52 | promises != null && Array.isArray(promises) && promises.length > 0, |
| 53 | () => 'promises must be a none empty array'); |
| 54 | } |
| 55 | |
| 56 | function checkFraction(startFraction: number, endFraction: number): void { |
| 57 | assert( |
| 58 | startFraction >= 0 && startFraction <= 1, |
| 59 | () => `Progress fraction must be in range [0, 1], but ` + |
| 60 | `got startFraction ${startFraction}`); |
| 61 | assert( |
| 62 | endFraction >= 0 && endFraction <= 1, |
| 63 | () => `Progress fraction must be in range [0, 1], but ` + |
| 64 | `got endFraction ${endFraction}`); |
| 65 | assert( |
| 66 | endFraction >= startFraction, |
| 67 | () => `startFraction must be no more than endFraction, but ` + |
| 68 | `got startFraction ${startFraction} and endFraction ` + |
| 69 | `${endFraction}`); |
| 70 | } |
| 71 | |
| 72 | return Promise.all(promises.map(registerMonitor)); |
| 73 | } |
no test coverage detected
searching dependent graphs…