-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy path0-async.js
More file actions
61 lines (49 loc) · 1.05 KB
/
0-async.js
File metadata and controls
61 lines (49 loc) · 1.05 KB
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
'use strict';
class AsyncMutex {
#queue = [];
#held = false;
enter() {
if (!this.#held) {
this.#held = true;
return Promise.resolve();
}
return new Promise((resolve) => {
this.#queue.push(resolve);
});
}
leave() {
const next = this.#queue.shift();
if (next) return void queueMicrotask(next);
this.#held = false;
}
}
// Usage
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
class Account {
#mutex = new AsyncMutex();
#balance = 0;
get balance() {
return this.#balance;
}
async deposit(amount, workTime) {
await this.#mutex.enter();
try {
const before = this.#balance;
await delay(workTime);
this.#balance = before + amount;
return this.#balance;
} finally {
this.#mutex.leave();
}
}
}
const main = async () => {
const account = new Account();
await Promise.all([
account.deposit(10, 50),
account.deposit(20, 10),
account.deposit(30, 5),
]);
console.log(account.balance);
};
main().catch(console.error);