Guest User

Untitled

a guest
Dec 18th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.94 KB | None | 0 0
  1. // idea, we want to start two async processes a and b.
  2.  
  3. const a = async () => { do_async_stuff() }
  4. const b = async () => { do_async_stuff() }
  5.  
  6. // but we need to isolate them. So b should not run before a
  7.  
  8. const result = Promise.all([a, b])
  9.  
  10. // this way they can overlap, not good. So lets use a lock
  11.  
  12. const lock = createLock()
  13. const a = async () => lock.atomic(() => do_async_stuff())
  14. const b = async () => lock.atomic(() => do_async_stuff())
  15.  
  16. // this implements createLock:
  17.  
  18. function createLock() {
  19. let locked = false
  20. const atomic = (fun) => {
  21. return new Promise(function(resolve, reject) {
  22. const rec = () => {
  23. if (locked) {
  24. setTimeout(rec, 0)
  25. } else {
  26. locked = true
  27. fun().then(res => {
  28. resolve(res)
  29. locked = false
  30. }, (err) => {
  31. reject(err)
  32. locked = false
  33. })
  34. }
  35. }
  36. rec()
  37. })
  38. }
  39.  
  40. return {
  41. atomic
  42. }
  43. }
Add Comment
Please, Sign In to add comment