【发布时间】: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