by artursapek · 10y ago · 0 comments
https://gist.github.com/artursapek/70437f6cdb562b7b62e910fd3...
Usage:
import Mutex from 'lib/mutex';
class MyObject {
constructor() {
this.m = new Mutex();
}
async someNetworkCall() {
let unlock = await this.m.lock();
doSomethingAsynchronous().then((result) => {
// handle result
unlock();
}).catch((err) => {
// handle error
unlock();
});
}
}
let mo = new MyObject();
mo.someNetworkCall();
// The next call will wait until the first call is finished
mo.someNetworkCall();
I love it. We use it in our production codebase at Codecademy. async someNetworkCall() {
let unlock = await this.m.lock();
try {
const result = await doSomethingAsynchronous();
// handle result
} catch (exception) {
// handle error
}
unlock();
}Their semaphore approach allows then to start an operation exactly X amounts of time and the next one will wait until another one finishes. Seems like an interesting approach. e.g. to limit the number of parallel connections.
Classes in JS!! what kind of witchcraft is that? How do you do it?
It's free to read and a good primer for how things have changed in JS-land in the last few years.