Last active
November 20, 2018 21:40
-
-
Save jeremyben/2be14402b98e422a5b047812210da7de to your computer and use it in GitHub Desktop.
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
/** | |
* Use with await to have synchrone delay | |
*/ | |
const delay = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms)) | |
/** | |
* Retry a promise a number of times if it failed | |
*/ | |
async function retry<T>(promise: Promise<T>, maxRetries: number, delayBetweenRetriesMs: number = 0) { | |
let res: T | |
let i = 0 | |
while (i < maxRetries) { | |
try { | |
res = await promise | |
break | |
} catch (err) { | |
i++ | |
await new Promise(resolve => setTimeout(resolve, delayBetweenRetriesMs)) | |
} | |
} | |
return res! | |
} | |
/** | |
* Executes all promises one after the other and retrieve all results | |
*/ | |
function sequenceAll<T>(tasks: Promise<T>[]): Promise<T[]> { | |
return tasks.reduce(async (prevTask, task) => { | |
const results: T[] = await prevTask | |
const result = await task | |
return results.concat(result) | |
}, Promise.resolve([])) | |
} | |
/** | |
* Executes all promises one after the other and retrieve only result of last promise | |
*/ | |
function sequenceLast<T>(tasks: Promise<T>[]): Promise<T> { | |
return tasks.reduce((prevTask, task) => prevTask.then(() => task), Promise.resolve(<unknown>null) as Promise<T>) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment