javascript - 如何使for循环同步?

标签 javascript 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.');

输出

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/

相关文章:

javascript - 如何使用监听器打印参数而不是值。另外,当我的字符串返回 null 作为每个输出的前缀时,会出现什么问题?

javascript - 用 Restify 抽象 Mongoose

javascript - 有没有一种简单的方法使用 Node.js 发送 POST 请求?

javascript - 使用 Node.JS,如何将 JSON 文件读入(服务器)内存?

javascript - Node.js 的循环模块

javascript - 如何在 Node 上正确重试 try 语句?

javascript - 尝试从我放入纬度和经度数据的 URL 获取 JSON 时,脚本不起作用

javascript - parseInt() - PHP 中字符串到整数再返回

javascript - firebase 登录后 TypeScript 返回对象

node.js - ## Node 纤维有问题##