Skip to content

Commit a36d585

Browse files
committed
Implement await locks.request
1 parent 1d9a67a commit a36d585

1 file changed

Lines changed: 8 additions & 10 deletions

File tree

JavaScript/9-web-locks.js

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,22 +19,21 @@ class Mutex {
1919
this.callback = null;
2020
}
2121

22-
enter(callback) {
22+
async enter(callback) {
2323
this.callback = callback;
2424
this.trying = true;
25-
this.tryEnter();
25+
await this.tryEnter();
2626
}
2727

28-
tryEnter() {
28+
async tryEnter() {
2929
if (!this.callback) return;
3030
const prev = Atomics.exchange(this.lock, 0, LOCKED);
3131
if (prev === UNLOCKED) {
3232
this.owner = true;
3333
this.trying = false;
34-
this.callback(this).then(() => {
35-
this.leave();
36-
});
34+
await this.callback(this);
3735
this.callback = null;
36+
this.leave();
3837
}
3938
}
4039

@@ -49,16 +48,15 @@ class Mutex {
4948
const locks = {
5049
resources: new Map(),
5150

52-
request: (resourceName, callback) => {
51+
request: async (resourceName, callback) => {
5352
let lock = locks.resources.get(resourceName);
5453
if (!lock) {
5554
const buffer = new SharedArrayBuffer(4);
5655
lock = new Mutex(resourceName, buffer, true);
5756
locks.resources.set(resourceName, lock);
5857
locks.sendMessage({ kind: 'create', resourceName, buffer });
5958
}
60-
lock.enter(callback);
61-
return lock;
59+
await lock.enter(callback);
6260
},
6361

6462
sendMessage: message => {
@@ -112,7 +110,7 @@ if (isMainThread) {
112110
new Thread();
113111
setTimeout(() => {
114112
process.exit(0);
115-
}, 200);
113+
}, 300);
116114

117115
} else {
118116

0 commit comments

Comments
 (0)