Skip to content

Instantly share code, notes, and snippets.

@vlio20
Created July 11, 2018 05:26
Show Gist options
  • Save vlio20/e8dd66423cacd1332bd580154147625a to your computer and use it in GitHub Desktop.
Save vlio20/e8dd66423cacd1332bd580154147625a to your computer and use it in GitHub Desktop.
Promise all (not fail fast) with controlled concurrent requests
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