Advertisement
Guest User

Untitled

a guest
Aug 22nd, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.83 KB | None | 0 0
  1. const work = (() => {
  2. let workload = []
  3. let cursor = null
  4.  
  5. setImmediate(async () => {
  6. while (true) {
  7. const workload = await next()
  8.  
  9. // implement as much as possible outside the loop
  10. for (const { context, args, resolve, reject } of workload) {
  11. reject(new Error('not implemented'))
  12. }
  13. }
  14. })
  15.  
  16. const next = () => new Promise(resolve => {
  17. cursor = () => {
  18. if (workload.length === 0) return
  19. cursor = null
  20. const nextWorkload = [...workload]
  21. workload = []
  22. resolve(nextWorkload)
  23. }
  24. cursor()
  25. })
  26.  
  27. return function work (...args) {
  28. const context = this
  29. return new Promise((resolve, reject) => {
  30. workload.push({ context, args, resolve, reject })
  31. if (typeof cursor === 'function') cursor()
  32. })
  33. }
  34. })()
  35.  
  36. work().then(console.log).catch(console.error)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement