我正在尝试使用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),但这意味着需要在我使用异步的地方更改整个应用程序代码。
我做错了什么?
如有任何帮助,我们将非常感谢:)
发布于 2019-06-25 17:31:23
continuation-local-storage似乎根本不支持promises。我发现cls-hooked是这样的(正如前面的回答所说的那样)。
这确实非常奇怪,这些库已经存在2年了,没有任何提交,而且似乎没有其他方法在节点中实现这一点……
发布于 2018-12-03 08:54:37
你有没有尝试过使用cls-hooked而不是continuation local-storage。我有一个类似的问题,它解决了它。
https://stackoverflow.com/questions/44758311
复制相似问题