如何在 Node.js 中等待
这是一个关于我认为 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 循环永远不会放弃控制,我认为这是有道理的。但是,我如何告诉等待函数尝试队列中的下一个回调?
Here is a question about what I would think would be a simple pattern in node js.
Here is my example in coffeescript:
db_is_open = false
db.open ->
db_is_open = true
wait = ->
wait() until db_is_open
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()};
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当我有一些需要同步运行的代码时,我喜欢使用异步模块。
I like to use the async module when I have bits of code that need to run synchronously.
为什么要等待,而不是仅仅使用在传递给 db.open 的函数内部运行的回调?这几乎是惯用的 Node 代码:
基本上,您应该简单地遵循 文档中列出的模式。
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:Basically, you should simply follow the patterns laid out in the documentation.