Created
July 19, 2021 22:31
-
-
Save martynchamberlin/20044ca3b33a3b0b4592caae67ae00de to your computer and use it in GitHub Desktop.
Serialize a series of async requests called simultaneously
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
const promises: Record<string, Promise<void>> = {}; | |
/** | |
* Serializes a series of promise-returning function calls to ensure they | |
* occur linearly (as FIFO) rather than concurrently. To group calls that | |
* are to be serialized together, send a matching key. | |
*/ | |
export async function serialize(key: string, callback: () => Promise<void>) { | |
if (promises[key]) { | |
await promises[key]; | |
} | |
if (!promises[key]) { | |
promises[key] = callback(); | |
await promises[key]; | |
delete promises[key]; | |
} else { | |
serialize(key, callback); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment