Skip to content

Instantly share code, notes, and snippets.

@mlankenau
Last active December 18, 2018 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mlankenau/c5b63d9812ab3ded0d204e3039558306 to your computer and use it in GitHub Desktop.
Save mlankenau/c5b63d9812ab3ded0d204e3039558306 to your computer and use it in GitHub Desktop.
// 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