如何使其循环同步?
代码
// (...)
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
的调用是同步的,因此您必须调用一个执行异步操作的函数(正如我在下面提到的)。 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 的调用可能不是同步的。如果您想要同步调用,则必须调用事物的 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);
}
关于javascript - 如何使for循环同步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4540031/