Created
March 13, 2024 22:56
-
-
Save zo0m/68d5f8a4ca94d8d57898896be3c627af to your computer and use it in GitHub Desktop.
shareExecution
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
(async function(){ | |
const shareExecution = (callback) => { | |
let loading; | |
return async function () { | |
if (!loading) { | |
loading = callback(); | |
loading.finally(() => loading = null) | |
} | |
return loading; | |
} | |
}; | |
async function delay(ms) { | |
return new Promise(resolve => setTimeout(resolve, ms)); | |
} | |
let callCount = 0; | |
const shared = shareExecution(() => delay(3000).then(() => callCount++)); | |
shared().then((c) => console.log(c, 1)); | |
shared().then((c) => console.log(c, 2)); | |
shared().then((c) => console.log(c, 3)); | |
await delay(1000); | |
shared().then((c) => console.log(c, 4)); | |
await delay(4000); | |
shared().then((c) => console.log(c, 'new')); | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment