【问题标题】:continuation-local-storage context is lost in async waterfallcontinuation-local-storage 上下文在异步瀑布中丢失
【发布时间】:2019-06-25 17:31:23
【问题描述】:

我正在尝试使用 continuation-local-storage 模块在我的整个应用程序中使用“currentUser”。

当调用异步瀑布时,上下文会丢失。

        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')})
                })
            }
        )

控制台打印是

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

解决这个问题是通过包装 ns.bind(fn2) 但这意味着需要更改整个应用程序代码以适应我有异步的地方。

我做错了什么?

任何帮助表示赞赏:)

【问题讨论】:

  • 您的编辑删除了您问题的相关部分,即您使用的是continuation-local-storage
  • 哇...感谢您指出这一点
  • 您找到解决方案了吗?

标签: node.js continuation-local-storag


【解决方案1】:

continuation-local-storage 似乎根本不适用于 Promise。我发现cls-hooked 确实如此(正如前面的答案已经说过的那样)。

确实很奇怪,这些库已经有 2 年历史而没有任何提交,而且似乎没有其他方法可以在节点中实现这一点......

【讨论】:

    【解决方案2】:

    您是否尝试过使用 cls-hooked 而不是 continuation-local-storage。我有一个类似的问题,它解决了它。

    【讨论】:

      猜你喜欢
      • 2015-07-18
      • 2018-11-13
      • 2020-09-06
      • 2014-10-31
      • 1970-01-01
      • 2015-04-28
      • 1970-01-01
      • 2019-01-02
      相关资源
      最近更新 更多