AsyncQueue.js 688 B

123456789101112131415161718192021222324252627282930
  1. class AsyncQueue {
  2. constructor() {
  3. this._queue = []
  4. this.canGet = new Promise(resolve => {
  5. this.resolveGet = resolve
  6. })
  7. this.canPush = true
  8. }
  9. async push(value) {
  10. await this.canPush
  11. this._queue.push(value)
  12. this.resolveGet(true)
  13. this.canPush = new Promise(resolve => {
  14. this.resolvePush = resolve
  15. })
  16. }
  17. async pop() {
  18. await this.canGet
  19. const returned = this._queue.pop()
  20. this.resolvePush(true)
  21. this.canGet = new Promise(resolve => {
  22. this.resolveGet = resolve
  23. })
  24. return returned
  25. }
  26. }
  27. module.exports = AsyncQueue