forked from tradle/asyncstorage-down
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtaskqueue.js
36 lines (29 loc) · 794 Bytes
/
taskqueue.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
'use strict';
var argsarray = require('argsarray');
var Queue = require('tiny-queue');
// see http://stackoverflow.com/a/15349865/680742
var nextTick = global.setImmediate || process.nextTick;
function TaskQueue() {
this.queue = new Queue();
this.running = false;
}
TaskQueue.prototype.add = function (fun, callback) {
this.queue.push({fun: fun, callback: callback});
this.processNext();
};
TaskQueue.prototype.processNext = function () {
var self = this;
if (self.running || !self.queue.length) {
return;
}
self.running = true;
var task = self.queue.shift();
nextTick(function () {
task.fun(argsarray(function (args) {
task.callback.apply(null, args);
self.running = false;
self.processNext();
}));
});
};
module.exports = TaskQueue;