Last active
December 18, 2018 15:15
-
-
Save mlankenau/c5b63d9812ab3ded0d204e3039558306 to your computer and use it in GitHub Desktop.
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
// idea, we want to start two async processes a and b. | |
const a = async () => { do_async_stuff() } | |
const b = async () => { do_async_stuff() } | |
// but we need to isolate them. So b should not run before a | |
const result = Promise.all([a, b]) | |
// this way they can overlap, not good. So lets use a lock | |
const lock = createLock() | |
const a = async () => lock.atomic(() => do_async_stuff()) | |
const b = async () => lock.atomic(() => do_async_stuff()) | |
// this implements createLock: | |
function createLock() { | |
let locked = false | |
const atomic = (fun) => { | |
return new Promise(function(resolve, reject) { | |
const rec = () => { | |
if (locked) { | |
setTimeout(rec, 0) | |
} else { | |
locked = true | |
fun().then(res => { | |
resolve(res) | |
locked = false | |
}, (err) => { | |
reject(err) | |
locked = false | |
}) | |
} | |
} | |
rec() | |
}) | |
} | |
return { | |
atomic | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment