forked from pouchdb/pouchdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
taskqueue.js
68 lines (61 loc) · 1.43 KB
/
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
'use strict';
module.exports = TaskQueue;
function TaskQueue() {
this.isReady = false;
this.failed = false;
this.queue = [];
}
TaskQueue.prototype.execute = function () {
var d, func;
if (this.failed) {
while ((d = this.queue.shift())) {
if (typeof d === 'function') {
d(this.failed);
continue;
}
func = d.parameters[d.parameters.length - 1];
if (typeof func === 'function') {
func(this.failed);
} else if (d.name === 'changes' && typeof func.complete === 'function') {
func.complete(this.failed);
}
}
} else if (this.isReady) {
while ((d = this.queue.shift())) {
if (typeof d === 'function') {
d();
} else {
d.task = this.db[d.name].apply(this.db, d.parameters);
}
}
}
};
TaskQueue.prototype.fail = function (err) {
this.failed = err;
this.execute();
};
TaskQueue.prototype.ready = function (db) {
if (this.failed) {
return false;
} else if (arguments.length === 0) {
return this.isReady;
}
this.isReady = db ? true: false;
this.db = db;
this.execute();
};
TaskQueue.prototype.addTask = function (name, parameters) {
if (typeof name === 'function') {
this.queue.push(name);
if (this.failed) {
this.execute();
}
} else {
var task = { name: name, parameters: parameters };
this.queue.push(task);
if (this.failed) {
this.execute();
}
return task;
}
};