node-continuation-local-storage icon indicating copy to clipboard operation
node-continuation-local-storage copied to clipboard

Session gets lost if nesting promises

Open alexandruluca opened this issue 7 years ago • 4 comments

I'm using this package to create a session for the current user so I can access session inside nested promises, including mongoose plugins and so on. For whatever reason, the namespace exists too quick and the session get's lost.

I debugged your code a little bit and I came up with this solution for my problem. In context.js line 44 in the Namespace.prototype.run method I patched it like this

Namespace.prototype.run = function (fn) {
  var context = this.createContext();
  this.enter(context);
  try {
    var contextFnResult = fn(context);
	  return context;
  }
  catch (exception) {
    if (exception) {
      exception[ERROR_SYMBOL] = context;
    }
    this.exit(context);
    throw exception;
  }
  finally {
    context.res.on('finish', function() {
		this.exit(context);
    });
  }
};

Basically I simply exit the namespace on an error and always exit on response finish

context.res.on('finish', function() {
		this.exit(context);
    });

This way I am sure that my session is active untill I send back my response to the client

This works for me as intended. Are there any cons to this approach? Looking forward to your feedback

alexandruluca avatar May 05 '17 09:05 alexandruluca

Had to use almost the same approach.

https://github.com/AleksMeshkov/node-continuation-local-storage/commit/7eee8cf67a4c3f79ca69bd7b5246c183dbdaaedd

AleksMeshkov avatar Aug 23 '17 11:08 AleksMeshkov

@AleksMeshkov have you opened a pull request? This will be a problem for anyone using CLS with express.

zsteinkamp avatar Sep 08 '17 18:09 zsteinkamp

@othiym23 Do we need a test for @AleksMeshkov s fix in a pull request?

sonicoder86 avatar Oct 30 '17 12:10 sonicoder86

Have you tried using ns.bindEmitter(res)?

Seems likely there is a branch of the execution tree that CLS is not aware of, resulting in the tree resolving early and exiting when some activity is still pending. The most likely cause of that is event emitters as they are not patched automatically.

Qard avatar Nov 01 '17 05:11 Qard