forked from nathan7/then-queue
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
41 lines (37 loc) · 948 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
'use strict';
var EventEmitter = require('events').EventEmitter
var Promise = require('promise')
module.exports = Queue
function Queue() {
if (!(this instanceof Queue)) return new Queue()
EventEmitter.call(this)
this._items = []
this._waiting = []
this.length = 0
}
Queue.prototype = Object.create(EventEmitter.prototype)
Queue.prototype.constructor = Queue
Queue.prototype.push = function(item) {
this.length++
this.emit('length-changed', this.length)
if (this._waiting.length) {
var waiting = this._waiting.shift()
waiting(item)
}
else {
this._items.push(item)
}
}
Queue.prototype.pop = function(cb) { var self = this
this.length--
this.emit('length-changed', this.length)
if (this._items.length) {
var item = this._items.shift()
return Promise.resolve(item).nodeify(cb)
}
else {
return new Promise(function(resolve, reject) {
self._waiting.push(resolve)
}).nodeify(cb)
}
}