-
Notifications
You must be signed in to change notification settings - Fork 0
/
node-mutex.js
67 lines (57 loc) · 1.72 KB
/
node-mutex.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
let mutex = Promise.resolve(); // global mutex instance
// Utility function to simulate some delay (e.g. reading from or writing to a database).
// It will take from 0 to 50ms in a random fashion.
const randomDelay = () =>
new Promise((resolve) => setTimeout(resolve, Math.random() * 3000));
// Our global balance.
// In a more complete implementation, this will live in the persistent data storage.
let balance = 0;
async function loadBalance() {
// simulates random delay to retrieve data from data storage
await randomDelay();
return balance;
}
async function saveBalance(value) {
// simulates random delay to write the data to the data storage
await randomDelay();
balance = value;
}
async function sellGrapes() {
mutex = mutex
.then(async () => {
const balance = await loadBalance();
console.log(`sellGrapes - balance loaded: ${balance}`);
const newBalance = balance + 50;
await saveBalance(newBalance);
console.log(`sellGrapes - balance updated: ${newBalance}`);
})
.catch(() => {});
console.log("sellGrapes", mutex);
return mutex;
}
async function sellOlives() {
mutex = mutex
.then(async () => {
const balance = await loadBalance();
console.log(`sellOlives - balance loaded: ${balance}`);
const newBalance = balance + 50;
await saveBalance(newBalance);
console.log(`sellOlives - balance updated: ${newBalance}`);
})
.catch(() => {});
console.log("sellOlives", mutex);
return mutex;
}
async function main() {
await Promise.all([
sellGrapes(),
sellOlives(),
sellGrapes(),
sellOlives(),
sellGrapes(),
sellOlives(),
]);
const balance = await loadBalance();
console.log(`Final balance: ${balance}`);
}
main();