Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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
- }
- }
Add Comment
Please, Sign In to add comment