简体   繁体   English

在Node.JS中连接到数据库

[英]Connecting to a Database in Node.JS

For some special cases, like 'require' it makes sense to block the execution, to make things simpler. 对于某些特殊情况,例如“ require”,阻止执行以简化事情是有意义的。

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: 问题:

  1. node doesn't have the 'sleep' method. 节点没有“睡眠”方法。
  2. 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. 实际上,我已经通过使用茉莉花节点中的waitFor了,但是当我查看它的源代码时-它非常复杂,并且使用了phantomjs C扩展名。

And sadly, simple while(true){...} stuff doesn't works. 不幸的是,简单的while(true){...}东西不起作用。 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? 但是,也许可以以某种其他简单的方式来实现它,而无需额外的依赖,如phantomjs和复杂的C扩展?

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: 例如:

db.connect(function(conn, err) {
  if (err) throw err;
  // Put your program logic using the db connection here...
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM