Lior Rabin
Lior Rabin

Reputation: 11

continuation-local-storage context is lost in async waterfall

I'm trying to use continuation-local-storage module to have "currentUser" across my entire application.

When calling async waterfall the context gets lost.

        app.get('/testing/cls',
            function(req, res, next) {
                ns.run(function() {
                    ns.set('currentUser', req.user._id)
                    return next()
                })
            },
            function(req, res) {
                function fn1(cb) {
                    console.log('async fn1', ns.get('currentUser'))
                    return cb()
                }

                function fn2(cb) {
                    console.log('async fn2', ns.get('currentUser'))
                    cb()
                }

                function fn3(cb) {
                    console.log('async fn3', ns.get('currentUser'))
                    cb()
                }

                async.waterfall([
                    fn1,
                    fn2,
                    fn3
                ], function() {
                    console.log('async waterfall done', ns.get('currentUser'))
                    res.send({user: ns.get('currentUser')})
                })
            }
        )

The console prints are

27/6/2017-11:49:39 - info: (13405) - async fn1 58a1adaslkdjh32e
27/6/2017-11:49:39 - info: (13405) - async fn2
27/6/2017-11:49:39 - info: (13405) - async fn3
27/6/2017-11:49:39 - info: (13405) - async waterfall done

Fixing this problem is by wrapping ns.bind(fn2) but this means that need to change entire application code for wherever I have async.

What am I doing wrong?

Any help is appreciated :)

Upvotes: 1

Views: 1375

Answers (2)

estani
estani

Reputation: 26487

continuation-local-storage doesn't seem to work with promises at all. I've found out that cls-hooked does (as the previous answer already said).

It is indeed very strange that those libraries are already 2 Years old without any commit and there seems to be no other way to implement this in node...

Upvotes: 1

user285429
user285429

Reputation: 323

Have you tried use cls-hooked rather than continuation-local-storage. I had a similar problem and it fixed it.

Upvotes: 0

Related Questions