-
Notifications
You must be signed in to change notification settings - Fork 233
/
Copy pathqueue.js
58 lines (52 loc) · 1.49 KB
/
queue.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
// @jessie-check
/* eslint @typescript-eslint/no-floating-promises: "warn" */
import { makePromiseKit } from '@endo/promise-kit';
/**
* Return a function that can wrap an async or sync method, but
* ensures only one of them (in order) is running at a time.
*/
export const makeWithQueue = () => {
const queue = [];
// Execute the thunk at the front of the queue.
const dequeue = () => {
if (!queue.length) {
return;
}
const [thunk, resolve, reject] = queue[0];
// Run the thunk in a new turn.
void Promise.resolve()
.then(thunk)
// Resolve or reject our caller with the thunk's value.
.then(resolve, reject)
// Rerun dequeue() after settling.
.finally(() => {
queue.shift();
if (queue.length) {
dequeue();
}
});
};
/**
* @template {(...args: any[]) => any} T
* @param {T} inner
*/
return function withQueue(inner) {
/**
* @param {Parameters<T>} args
* @returns {Promise<Awaited<ReturnType<T>>>}
*/
return function queueCall(...args) {
// Curry the arguments into the inner function, and
// resolve/reject with whatever the inner function does.
const thunk = _ => inner(...args);
const pr = makePromiseKit();
queue.push([thunk, pr.resolve, pr.reject]);
if (queue.length === 1) {
// Start running immediately.
dequeue();
}
// Allow the caller to retrieve our thunk's results.
return pr.promise;
};
};
};