【问题标题】:How to make for cycle synchronous?如何使循环同步?
【发布时间】:2011-05-31 05:09:26
【问题描述】:

如何使这个循环同步?提前致谢。

代码

// (...)

object = {
  'item1': 'apple',
  'item2': 'orange'
};

// (...)

for(var key in object) {

  // do something async...
  request.on('response', function (response) {
    response.on('data', function (chunk) {

      console.log('The message was sent.');

    });
  });

}

console.log('The for cycle ended.');

输出

The for cycle ended.
The message was sent.

我想看看这种类型的输出...

The message was sent.
The for cycle ended.

【问题讨论】:

  • 欢迎来到 StackOverflow!您需要提供更多详细信息才能以合理的方式回答您的问题。事实上,按照现在的方式,您的问题可能会被社区视为“不是一个真正的问题”而关闭。不要让这困扰您,只需再试一次,了解更多细节。人们准备并愿意提供帮助。可能值得一读the FAQthis page on how to ask questions。最好的,
  • 谢谢你,T.J.克劳德。
  • Milo,您可以“编辑”您的问题以提供更多信息,而不是再次重新发布问题
  • @Matt 谢谢,马特。我刚刚编辑了我的问题。

标签: javascript javascript-events node.js


【解决方案1】:

更新答案

关于您更新的问题,对sendMessage 的调用是同步的,因此您必须调用一个执行异步操作的函数(如下所述)。 sendMessage 未在 NodeJS 文档中列出。您必须从获得它的任何来源找到它的同步版本,或者使用它的回调机制:

var obj, keys, key, index;

// Define the object
obj = {
  'item1': 'apple',
  'item2': 'orange'
};

// Find its keys (you can just type in the array if they don't
// need to be discovered dynamically)
keys = [];
for (key in obj) {
    keys.push(key);
}

// Start the loop
index = 0;
process();

// This function gets called on each loop
function process() {
    // Are we done?
    if (index >= keys.length) {
        // Yes
        console.log("The cycle ended");
    }
    else {
        // No, send the next message and then
        // use this function as the callback so
        // we send the next (or flag that we're done)
        sendMessage(obj[keys[index++]], process);
    }
}

原答案: 周期同步的。您必须执行 setTimeout 之类的操作或使其*a*同步。

不过,您对 NodeJS 的调用可能不是同步的。如果你想要同步调用,你必须调用 xyzSync 版本的东西。

继续猜测你的意思,如果你想让循环 *a*同步:

var obj, key;

// Define the object
obj = {
  'item1': 'apple',
  'item2': 'orange'
};

for (key in obj) {
  schedule(key);
}

function schedule(k) {
    setTimeout(function() {
        // Do something with obj[k]
    }, 0);
}

【讨论】:

  • @Milo:抱歉,只说更新代码的两个问题;固定。
【解决方案2】:

我不熟悉 node.js,但我认为:

function() {
  console.log('The message was sent.');
}

是一个回调函数,一旦消息发送成功就会被调用。并且消息的实际发送是异步的,以免阻塞其余的执行。如果你想让它成为一个阻塞/同步的过程,你可以这样做:(注意,在 node.js 中可能有一种显式的方式来进行同步调用,我只是不熟悉):

for(var key in object) {
  var completed = false;
  sendMessage('Hello!', function() {
    console.log('The message was sent.');
    completed = true;
  });

  while(completed == false) {
    ; // do nothing
  }
}

上述方法的缺点是,如果 sendMessage() 或回调中出现错误,您可能会发现自己处于 while() 语句的无限循环中。

另一种方法可以让您异步发送所有消息,然后等待它们全部完成,然后再继续进行操作,例如:

var count = 0;
for(var key in object) {
  count++;
  sendMessage('Hello!', function() {
    console.log('The message was sent.');
    count--;
  });
}

while(count > 0){ 
  ; // wait until all have finished
}

如果出现阻止计数再次达到 0 的错误,这将产生同样的无限循环问题。

【讨论】:

    猜你喜欢
    • 2013-03-31
    • 2011-06-24
    • 2015-01-12
    • 2023-01-20
    • 2014-07-06
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多