Created
February 21, 2020 13:32
-
-
Save MrAntix/a5eb8769f9a888c14e2263c408cb0bab to your computer and use it in GitHub Desktop.
This file contains 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 const PROMISE_SINGLETON_REJECTION_REASON = 'rejected by successor'; | |
/** | |
* Creates a context where by only the last called promise is resolved | |
* Previous ones would be rejected | |
* | |
* @example | |
* | |
* const context = createPromiseSingletonContext<string>(); | |
* const someApiCall = (result: string) => new Promise<string>(resolve => { | |
* setTimeout(() => resolve(result), 1000) | |
* }); | |
* | |
* let result: string; | |
* let rejectedErr: string; | |
* | |
* const call = async (attempt: string) => { | |
* try { | |
* | |
* result = await context(() => someApiCall('one')); | |
* | |
* } catch (err) { | |
* // You might abort a fetch here if needed | |
* rejectedErr = err; | |
* } | |
* } | |
* | |
* call('one'); | |
* await call('two'); | |
* | |
* > result | |
* < "two" | |
* | |
* > rejectedErr | |
* < "rejected by successor" | |
*/ | |
export function createPromiseSingletonContext<TResult>() { | |
let previous: (reason: string) => void; | |
return (action: () => Promise<TResult>) => { | |
if (previous) { | |
previous(PROMISE_SINGLETON_REJECTION_REASON); | |
previous = null; | |
} | |
return new Promise<TResult>(async (resolve, reject) => { | |
previous = reject; | |
resolve(await action()); | |
}); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment