Advertisement
Guest User

Untitled

a guest
Apr 19th, 2019
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.79 KB | None | 0 0
  1. let locked = false
  2.  
  3. const checkCanCall = (resolve) => {
  4. if (locked) {
  5. return setTimeout(() => checkCanCall(resolve), 100)
  6. }
  7. locked = true
  8. resolve()
  9. };
  10.  
  11. const waitUntilFree = () => new Promise(checkCanCall)
  12.  
  13. const unlock = () => locked = false
  14.  
  15. const synchronize = (action) => {
  16. return waitUntilFree()
  17. .then(() => action())
  18. .finally(unlock)
  19. };
  20.  
  21.  
  22. synchronize(() => {
  23. return new Promise((r) =>{
  24. setTimeout(r, 3000);
  25. }).then(r => {
  26. console.info('First Promise, after 3s')
  27. })
  28. }).then(()=>{
  29. console.info('After first promise')
  30. })
  31.  
  32. synchronize(() => {
  33. return new Promise((r) =>{
  34. setTimeout(r, 3000);
  35. }).then(r => {
  36. console.info('Second Promise, after 6s')
  37. })
  38. }).then(()=>{
  39. console.info('After second promise')
  40. })
  41.  
  42. console.info('Immediately executed, wait for 3s')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement