Javascript 如何使循环同步?

Javascript 如何使循环同步?,javascript,javascript-events,node.js,Javascript,Javascript Events,Node.js,如何使循环同步?提前谢谢 代码 // (...) object = { 'item1': 'apple', 'item2': 'orange' }; // (...) for(var key in object) { // do something async... request.on('response', function (response) { response.on('data', function (chunk) { console.l

如何使循环同步?提前谢谢

代码

// (...)

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.

更新的答案

更新后的问题是,对
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
的操作,或者使其*同步

不过,您对NodeJS的调用可能不是同步的。如果需要同步调用,则必须调用事物的
xyzync
版本

继续猜测您可能的意思,如果您想使循环*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);
}

更新的答案

更新后的问题是,对
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
的操作,或者使其*同步

不过,您对NodeJS的调用可能不是同步的。如果需要同步调用,则必须调用事物的
xyzync
版本

继续猜测您可能的意思,如果您想使循环*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);
}

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

function() {
  console.log('The message was sent.');
}
消息成功发送后调用的回调函数。消息的实际发送是异步的,这样就不会阻塞其余的执行。如果您想使其成为一个阻塞/同步过程,您可以这样做:(注意,在node.js中可能有一种显式的同步调用方法,我只是不太熟悉):

上述方法的缺点是,如果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,那么这将有与无限循环相同的问题。

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

function() {
  console.log('The message was sent.');
}
消息成功发送后调用的回调函数。消息的实际发送是异步的,这样就不会阻塞其余的执行。如果您想使其成为一个阻塞/同步过程,您可以这样做:(注意,在node.js中可能有一种显式的同步调用方法,我只是不太熟悉):

上述方法的缺点是,如果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,这将有与无限循环相同的问题。

欢迎使用StackOverflow!您需要提供更多的细节,以便以合理的方式回答您的问题。事实上,现在的情况是,你的问题可能会被社区认为“不是一个真正的问题”。别让这件事困扰你,再试一次,再详细一点。人们随时准备并愿意提供帮助。可能值得一读。最好,谢谢你,T.J.克劳德。米洛,你可以“编辑”你的问题以提供更多信息,而不是重新发布问题again@Matt谢谢,马特。我刚刚编辑了我的问题。欢迎来到StackOverflow!您需要提供更多的细节,以便以合理的方式回答您的问题。事实上,现在的情况是,你的问题可能会被社区认为“不是一个真正的问题”。别让这件事困扰你,再试一次,再详细一点。人们随时准备并愿意提供帮助。可能值得一读。最好,谢谢你,T.J.克劳德。米洛,你可以“编辑”你的问题以提供更多信息,而不是重新发布问题again@Matt谢谢,马特。我刚刚编辑了我的问题。@Milo:对不起,就更新代码说两个问题;修正了。@Milo:抱歉,只需说两个更新代码的问题;固定的。