如何在 Node.js 中等待 [英] How to Wait in Node.js

查看:23
本文介绍了如何在 Node.js 中等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

在 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 的函数内部运行的回调?这是非常惯用的 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:

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

基本上,您应该遵循文档中列出的模式.

Basically, you should simply follow the patterns laid out in the documentation.

这篇关于如何在 Node.js 中等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆