如何使循环同步?

0 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.log('The message was sent.');

    });
  });

}

console.log('The for cycle ended.');
Run Code Online (Sandbox Code Playgroud)

产量

The for cycle ended.
The message was sent.
Run Code Online (Sandbox Code Playgroud)

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

The message was sent.
The for cycle ended.
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 5

更新的答案:

更新你的更新问题,调用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

原答案:循环同步的.你必须做一些像setTimeout什么使它**同步.

但是,您对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);
}
Run Code Online (Sandbox Code Playgroud)