forked from pgte/fake-queue
/
index.js
45 lines (40 loc) · 909 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
42
43
44
45
var queues = {};
var waiting = {};
function notify(type) {
var clients = waiting[type]
, queue = queues[type]
, client
, job;
if (queue && clients) {
while (queue.length > 0 && clients.length > 0) {
client = clients.splice(0, 1)[0];
job = queue.splice(0, 1)[0];
(function(client, job) {
process.nextTick(function() {
client(job, function(err) {
if (err) { push(type, job); }
});
});
})(client, job);
}
}
}
function push(type, jobData, callback) {
if (! queues[type]) { queues[type] = []; }
queues[type].push(jobData);
notify(type);
if (callback) {
process.nextTick(callback);
}
}
function pop(type, callback) {
if (! waiting[type]) { waiting[type] = []; }
waiting[type].push(callback);
notify(type);
}
module.exports = function() {
return {
push: push
, pop: pop
};
};