Skip to content

Instantly share code, notes, and snippets.

@martynchamberlin
Created July 19, 2021 22:31
Show Gist options
  • Save martynchamberlin/20044ca3b33a3b0b4592caae67ae00de to your computer and use it in GitHub Desktop.
Save martynchamberlin/20044ca3b33a3b0b4592caae67ae00de to your computer and use it in GitHub Desktop.
Serialize a series of async requests called simultaneously
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