这是一个关于我认为 Node 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 循环永远不会放弃控制,我想这是有道理的。但是如何告诉等待函数尝试队列中的下一个回调?
最佳答案
我喜欢使用 async module当我有一些需要同步运行的代码时。
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')
}
})
关于node.js - 如何在 Node.js 中等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8881892/