Skip to content

Instantly share code, notes, and snippets.

@zo0m
Created March 13, 2024 22:56
Show Gist options
  • Save zo0m/68d5f8a4ca94d8d57898896be3c627af to your computer and use it in GitHub Desktop.
Save zo0m/68d5f8a4ca94d8d57898896be3c627af to your computer and use it in GitHub Desktop.
shareExecution
(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