Node.js and Mutexes

后端 未结 4 881
情深已故
情深已故 2020-12-25 10:51

I\'m wondering if mutexes/locks are required for data access within Node.js. For example, lets say I\'ve created a simple server. The server provides a couple protocol metho

4条回答
  •  长发绾君心
    2020-12-25 11:41

    Mutexes are definitely necessary for a lot of back end implementations. Consider a class where you need to maintain synchronicity of async execution by constructing a promise chain.

    let _ = new WeakMap();
    class Foobar {
      constructor() {
        _.set(this, { pc : Promise.resolve() } );
      }
      doSomething(x) {
        return new Promise( (resolve,reject) => {
          _.get(this).pc = _.get(this).pc.then( () => {
            y = some value gotten asynchronously
            resolve(y);
          })
        })
      }
    }
    

    How can you be sure that a promise is not left dangling via race condition? It's frustrating that node hasn't made mutexes native since javascript is so inherently asynchronous and bringing third party modules into the process space is always a security risk.

提交回复
热议问题