Skip to content

Instantly share code, notes, and snippets.

@quickshiftin
Created December 15, 2023 17:15
Show Gist options
  • Save quickshiftin/05dda15be715bd4255b494b715de92c8 to your computer and use it in GitHub Desktop.
Save quickshiftin/05dda15be715bd4255b494b715de92c8 to your computer and use it in GitHub Desktop.
Multiple clients that need access to an async resource can share a single call via promises
// if several clients latch on to the same promise, do they all receive the results?
let thePromise = null;
const getSharedPromise = () => {
// first time invocation, spin up the async activity
// (connect to db, fetch crypto price quote, etc, etc)
if(thePromise === null) {
thePromise = new Promise((resolve, reject) => {
setTimeout(() => {
thePromise = null;
resolve('something');
}, 2500);
});
}
// otherwise, return the current promise,
// which will resolve to the same result for everyone
return thePromise;
};
/**
* output:
*
client 1: something
client 2: something
client 3: something
*/
const client1 = getSharedPromise().then((r) => console.log(`client 1: ${r}`))
const client2 = getSharedPromise().then((r) => console.log(`client 2: ${r}`))
const client3 = getSharedPromise().then((r) => console.log(`client 3: ${r}`))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment