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.
It's quite an interesting approach for limiting the amount of concurrency in singlethreaded environments. I first saw that in the documentation of the C++ seastar library which is also mostly a singlethreaded eventloop. See the chapter "Limiting parallelism with semaphores" here: http://docs.seastar-project.org/master/md_doc_tutorial.html
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.
Why do you need mutexes in a single threaded context ? If you need sequential async operations that's what async await are for. What if you need to return something from someNetworkCall ? yes you're f..cked in that case.
Presumably instances of `MyObject` can be accessed by functions which are running while this function is suspended, waiting for the network call. It's single threaded, as in only one thing happens at a time from JS's point of view, but other functions can be invoked (by a request coming in, or a UI event etc) while an asynchronous operation is awaiting completion.
That's not true. You could return (either the promise being used or a directly awaited value) and that value would be made available through await / promise as well.
https://gist.github.com/artursapek/70437f6cdb562b7b62e910fd3...
Usage:
I love it. We use it in our production codebase at Codecademy.