连接到 Node.JS 中的数据库
对于某些特殊情况,例如“require”,阻止执行是有意义的,以使事情变得更简单。
我有一个类似的情况,我需要一种方法来建立数据库连接,但被阻止。 而且,因为它只发生一次 - 当应用程序启动并保存在全局对象中以供以后重用时 - 它不会影响性能。
问题:
- 节点没有“睡眠”方法。
- 事件循环有一些技巧,您必须阻止它,但同时允许处理数据库连接的内容。
实际上我已经通过使用 jasmine-node 中的 waitFor
做到了,但是当我查看它的源代码时 - 它非常复杂并且使用 phantomjs C 扩展。
可悲的是,简单的 while(true){...}
东西不起作用。例如,下面的代码不起作用,我相信是因为它阻止了事件循环并且不允许节点处理它等待的事件(在单线程环境中有点死锁:))。
waitsFor = (fun, message = "waitsFor timeout!", timeout = 1000) ->
start = new Date().getTime()
while true
if fun()
break
else if (new Date().getTime() - start) > timeout
throw new Error(message)
但是,也许可以通过其他一些简单的方式来完成它,而不需要像 phantomjs 和复杂的 C 扩展这样的额外依赖项?
For some special cases, like 'require' it makes sense to block the execution, to make things simpler.
I have a similar case, I need a way to make DB connection, blocked.
And, because it happens only one time - when the app started and saved in global object for later reuse - it will not affect the performance.
The problems:
- node doesn't have the 'sleep' method.
- there's some trickery with event loop, You has to block it, but at the same time allow to process it the database connection stuff.
Actually I already did it, by using waitFor
from jasmine-node, but when I looked at it source - it's very complicated and uses phantomjs C-extensions.
And sadly, simple while(true){...}
stuff doesn't works. For example, code below doesn't work, I believe because it blocks the event loop and doesn't allow node to process the event it waits for (sort of deadlock in single-threaded environment :) ).
waitsFor = (fun, message = "waitsFor timeout!", timeout = 1000) ->
start = new Date().getTime()
while true
if fun()
break
else if (new Date().getTime() - start) > timeout
throw new Error(message)
But, maybe it's somehow possible to do it in some other simple way, without extra dependencies like phantomjs
and complicated C-extensions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的应用程序应首先尝试异步连接到数据库,然后在连接可用时继续执行其处理逻辑。例如:
Your application should first attempt to connect to the database asynchronously and then proceed with its processing logic when the connection is available. For example: