延迟事件直到调用回调 (Node.js)
我将 Node.js 与 Express 结合使用,并且在我的路线中具有与此类似的代码:
requireLogin: function(req, res, next) {
User.find(req.session.userId)
.on('success', function(user) {
req.addListener('data', function(chunk) {
console.log("DATA: " + chunk);
}
next()
}
}
我正在使用 Sequelize,并且 User.find 方法正在访问数据库。问题是,我绑定的请求“数据”事件永远不会被触发。当用户从数据库返回时,数据事件似乎已经被触发和处理,现在用它做任何事情都为时已晚。在上面的示例中,我可以将 req.addListener 移动到数据库回调之外,但实际上我在这里调用了无法移动的 next() 。
接下来由 next() 调用的所有路由中间件都无法访问请求数据,因为这些事件已经被触发。更糟糕的是,它们只是挂起等待来自 req 的数据事件,因为它已经发生了。
如何以某种方式延迟数据事件,以便可以将其绑定到数据库回调中?或者我是否误解了一些根本性的东西并且需要改变我的处理方式?
多谢。
编辑:我在 nodejs Google 群组中找到了相关讨论,其中建议没有适合我的解决方案。
I am using Node.js with Express and have code similar to this as part of my routes:
requireLogin: function(req, res, next) {
User.find(req.session.userId)
.on('success', function(user) {
req.addListener('data', function(chunk) {
console.log("DATA: " + chunk);
}
next()
}
}
I am using Sequelize and the User.find method is accessing the database. The trouble is, the request 'data' event that I bind to is never fired. It seems that the data event had already been triggered and handled by the time the user is returned from the database and it's too late to do anything with it. In the example above I could just move the req.addListener to outside the database callback, but in reality I am calling next() here which can't be moved.
All of the following route middleware that is called by next() then doesn't have access to the request data since these events have already been fired. Worse than that, they just hang waiting for the data event from req because it has already happened.
How can I somehow delay the data event so that it can be bound to from within the database callback? Or have I misunderstood something fundamental and need to change my way of going about this?
Thanks a lot.
Edit: I found a relevant discussion in the nodejs Google group which suggests there isn't a solution that will work for me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您真正想要的是某种消息缓存。现在这是一个模糊的概念证明。你真正想要什么取决于你的代码。
如果您有任何类型的延迟库/抽象可用,那么代码将变得小很多。
I presume what you actually want is some kind of message caching. Now this is a vague proof of concept. What you actually want depends on your code.
If you have any kind of deferred library / abstraction available then the code will become a lot smaller.