如何等待Node.js [英] How to Wait in Node.js
本文介绍了如何等待Node.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这里是一个关于我认为在节点js中的简单模式的问题。
Here is a question about what I would think would be a simple pattern in node js.
这是我在coffeescript中的示例:
Here is my example in coffeescript:
db_is_open = false
db.open ->
db_is_open = true
wait = ->
wait() until db_is_open
再次在javascript中:
And here again in javascript:
var db_is_open = false;
db.open(function() {
db_is_open = true;
});
function wait() {};
while (not db_is_open) { wait()};
这根本不工作,因为while循环从不放弃控制,我猜这是有意义的。但是如何告诉等待函数来尝试队列中的下一个回调呢?
This does not work at all because the while loop never relinquishes control, which I guess makes sense. However how can I tell the wait function to try the next callback in the queue?
推荐答案
为什么要等待,使用在传递给 db.open
的函数内部运行的回调?这是几乎成语节点代码:
Why are you waiting, and not just using a callback that runs inside of the function passed to db.open
? This is pretty much idiomatic Node code:
db.open(function() {
// db is now open, let's run some more code
execute_db_query();
});
基本上,你应该遵循文档。
这篇关于如何等待Node.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文