Created
July 11, 2018 05:26
-
-
Save vlio20/e8dd66423cacd1332bd580154147625a to your computer and use it in GitHub Desktop.
Promise all (not fail fast) with controlled concurrent requests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export interface ISuccessError { | |
success: boolean; | |
result?: any; | |
error?: any; | |
} | |
type PromFucn = (...args: any[]) => Promise<any>; | |
promiseAllConcurrent(promFuncs: PromFucn[], | |
concurrent: number = 1): Promise<ISuccessError[]> { | |
const responses: ISuccessError[] = new Array(promFuncs.length); | |
const firstArr = promFuncs.slice(0, Math.min(promFuncs.length, concurrent)); | |
let nextFuncIndex = firstArr.length - 1; | |
const executor: (i: number) => Promise<void> = (i: number) => { | |
return this.wrapPromise(promFuncs[i]()) | |
.then((resp) => { | |
responses[i] = resp; | |
nextFuncIndex++; | |
if (promFuncs[nextFuncIndex]) { | |
return executor(nextFuncIndex); | |
} | |
}); | |
}; | |
wrapPromise(promise: Promise<any>): Promise<ISuccessError> { | |
return promise | |
.then(result => ({success: true, result})) | |
.catch(error => ({success: false, error})); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment