Hacker News new | past | comments | ask | show | jobs | submit login

You can use async/await to implement a Mutex in ES6! It's crazy.

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.



You can use the await keyword multiple times, and therefore make it easier to handle the error with try catch:

      async someNetworkCall() {
        let unlock = await this.m.lock();

        try {
          const result = await doSomethingAsynchronous();
          // handle result
        } catch (exception) {
          // handle error
        }
        unlock();
      }


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.


I feel like I know nothing about js/node anymore,

Classes in JS!! what kind of witchcraft is that? How do you do it?


I'll recommend the You Don't Know JS series: https://github.com/getify/You-Dont-Know-JS

It's free to read and a good primer for how things have changed in JS-land in the last few years.


It was introduced in ES6. It's still using prototyping behind the scenes, but it's quite a bit nicer to look at.


thanks, I will check it.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: