Skip to content

Instantly share code, notes, and snippets.

@afshin-hoseini
Created July 10, 2021 15:57
Show Gist options
  • Save afshin-hoseini/861d47bd444937da960db451e3964588 to your computer and use it in GitHub Desktop.
Save afshin-hoseini/861d47bd444937da960db451e3964588 to your computer and use it in GitHub Desktop.
How to serialize asynchronous calls to an async function in javascript
/*
*/
function serialized(fn){
let queue = Promise.resolve();
return (...args)=>{
const res = queue.then(() => fn(...args));
queue = res.catch(() => {});
return res;
}
}
const myAsyncTask = (title, wait, fail=false)=>{
return new Promise((resolve, reject)=>{
setTimeout(()=>{
if(fail)
reject()
else
resolve()
}, wait)
})
}
const serializedAsyncTask = serialized(myAsyncTask);
serializedAsyncTask("T1", 2000).then(_=>console.log(`T1 - ✓`)).catch(_=>console.log(`T1 - 𐄂`))
serializedAsyncTask("T2", 1000, true).then(_=>console.log(`T2 - ✓`)).catch(_=>console.log(`T2 - 𐄂`))
serializedAsyncTask("T3", 500).then(_=>console.log(`T3 - ✓`)).catch(_=>console.log(`T3 - 𐄂`))
@afshin-hoseini
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment