-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path4-id-perf.js
54 lines (50 loc) · 1.72 KB
/
4-id-perf.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
'use strict';
const { AsyncLocalStorage } = require('node:async_hooks');
const application = {
asyncLocalStorage: new AsyncLocalStorage(),
state: {
marcus: { name: 'Marcus', balance: 1000 },
lucius: { name: 'Lucius', balance: 1000 },
},
api: {
pay: async (from, to, amount) => {
const id = application.asyncLocalStorage.getStore();
const { available } = await application.api.check(from, amount);
if (!available) return { id, amount: 0, success: false };
const { money } = await application.api.withdraw(from, amount);
await application.api.topup(to, money);
return { id, amount, success: true };
},
withdraw: async (account, amount) => {
const id = application.asyncLocalStorage.getStore();
account.balance -= amount;
return { id, money: amount };
},
topup: async (account, amount) => {
const id = application.asyncLocalStorage.getStore();
account.balance += amount;
return { id, money: amount };
},
check: async (account, amount) => {
const id = application.asyncLocalStorage.getStore();
const available = account.balance >= amount;
return { id, available };
},
},
};
const test = async () => {
console.time('test');
const { marcus, lucius } = application.state;
for (let i = 0; i < 1000000; i++) {
application.asyncLocalStorage.run(i, async () => {
await application.api.pay(marcus, lucius, 150);
await application.api.pay(lucius, marcus, 200);
await application.api.pay(marcus, lucius, 250);
await application.api.pay(lucius, marcus, 400);
await application.api.pay(marcus, lucius, 200);
});
}
console.log(application.state);
console.timeEnd('test');
};
test();