Created
July 10, 2021 15:57
-
-
Save afshin-hoseini/861d47bd444937da960db451e3964588 to your computer and use it in GitHub Desktop.
How to serialize asynchronous calls to an async function in javascript
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
/* | |
*/ | |
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 - 𐄂`)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More info:
https://advancedweb.hu/how-to-serialize-calls-to-an-async-function/