forked from parse-community/parse-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKeyPromiseQueue.js
43 lines (40 loc) · 955 Bytes
/
KeyPromiseQueue.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
// KeyPromiseQueue is a simple promise queue
// used to queue operations per key basis.
// Once the tail promise in the key-queue fulfills,
// the chain on that key will be cleared.
export class KeyPromiseQueue {
constructor() {
this.queue = {};
}
enqueue(key, operation) {
const tuple = this.beforeOp(key);
const toAwait = tuple[1];
const nextOperation = toAwait.then(operation);
const wrappedOperation = nextOperation.then(result => {
this.afterOp(key);
return result;
});
tuple[1] = wrappedOperation;
return wrappedOperation;
}
beforeOp(key) {
let tuple = this.queue[key];
if (!tuple) {
tuple = [0, Promise.resolve()];
this.queue[key] = tuple;
}
tuple[0]++;
return tuple;
}
afterOp(key) {
const tuple = this.queue[key];
if (!tuple) {
return;
}
tuple[0]--;
if (tuple[0] <= 0) {
delete this.queue[key];
return;
}
}
}