如何在Node.js中等待

这是一个关于我认为会是节点js中简单模式的问题。

这是我在coffeescript的例子:

db_is_open = false db.open -> db_is_open = true wait = -> wait() until db_is_open 

并再次在JavaScript中:

 var db_is_open = false; db.open(function() { db_is_open = true; }); function wait() {}; while (not db_is_open) { wait()}; 

这根本不起作用,因为while循环从不放弃控制,我认为这是有道理的。 但是,我怎么能告诉等待函数尝试队列中的下一个callback?

为什么你在等待,而不是只使用传递给db.open的函数内部运行的callback? 这是非常习惯的节点代码:

 db.open(function() { // db is now open, let's run some more code execute_db_query(); }); 

基本上,您应该简单地遵循文档中列出的模式。

当我有一些代码需要同步运行时,我喜欢使用asynchronous模块 。

 var async = require('async'); async.series([ function(next){ db.open(next) } , function(next){ db.loadSite('siteName', next) } ], function(err){ if(err) console.log(err) else { // Waits for defined functions to finish console.log('Database connected') } })