简体   繁体   English

异步迭代对象键/值

[英]Iterating over object key/values asynchronously

Given this code: 给出以下代码:

var o = {
  k1: 'v1',
  k2: 'v2',
  k3: 'v3'
};

var stupidf = function(k, v, callback) {
  setTimeout(function() {
     console.log(k + "=" + v);
     callback();
  }, 2000};
};

What's the best way to produce the output: 产生输出的最佳方法是什么:

// after 2 seconds
stdout: k1=v1
// after 4 seconds
stdout: k2=v2
// after 6 seconds
stdout: k3=v3

With an array, you'd make a copy and push() it about with callbacks, but I can't really see how to do this with an object. 对于数组,您将创建一个副本并通过回调对其进行push() ,但是我真的看不到如何使用对象来实现。

You're assuming that the iteration of entries in o has a guaranteed order; 您假设o的条目迭代具有确定的顺序; it does not . 它没有 Assuming you don't care what order you get them out: 假设您不在乎将其取出的顺序:

function asyncIterate(o,callback,timeout){
  var kv=[], i=0;
  for (var k in o) if (o.hasOwnProperty(k)) kv.push([k,o[k]);
  var iterator = function(){
    callback(kv[i][0],kv[i][1]);
    if (++i < kv.length) setTimeout(iterator,timeout); 
  }
  setTimeout(iterator,timeout);
}
asyncIterate(o,function(k,v){
  console.log(k+'='+v);
},2000);

JavaScript does not have something like Lua's next() function that allows you to find the next key/value pair after a given one. JavaScript不像Lua的next()函数那样允许您在给定键/值对之后找到下一个键/值对。

If you do care about the order of the entries, then you need to store your original key/value pairs in an array, not an object. 如果您确实关心条目的顺序,则需要将原始键/值对存储在数组中,而不是对象中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM