如何在 Node.js 中等待

发布于 2024-12-27 09:53:37 字数 436 浏览 1 评论 0原文

这是一个关于我认为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一梦浮鱼 2025-01-03 09:53:37

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

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')
  }
})

I like to use the async module when I have bits of code that need to run synchronously.

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')
  }
})
葬花如无物 2025-01-03 09:53:37

为什么要等待,而不是仅仅使用在传递给 db.open 的函数内部运行的回调?这几乎是惯用的 Node 代码:

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

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文