"异步"遍历在JavaScript对象 [英] "Async" loop over an object in javascript

查看:197
本文介绍了"异步"遍历在JavaScript对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常情况下,我们可以做两个数组和对象遍历的属性/值循环。但是环路阻塞。然而,超时可以用来模拟一个异步循环。 我设法做它一个数组

Normally, we can do loops for both arrays and objects to iterate over the properties/values. But loops are blocking. However, timeouts can be used to simulate an async loop. i managed to do it for an array.

//do stuff

(function asyncLoop(i){

    //do stuff in the current iteration

    if(++i < array.length){
        setTimeout(function(){asyncLoop(i);}, 1);
    } else {
        callback();
    }
}(0));

//do stuff immediately after, while looping

但这种模式只,而在一个数组,那里是一个循环限工作 - 在 I 是被传来传去。有没有办法做到这一点了一个对象?让我们只说对象具有50K键遍历,使其过长。

but this model only works while looping in an array, where there is a limiter - the i that gets passed around. is there a way to do this over an object? let's just say that the object has 50k keys to iterate through, making it unreasonably long.

我已经知道了这个 setImmediate (据我所知,只有较新的IE)和的 WebWorkers (尚未在IE浏览器),但我只是想知道,如果有可能只使用了相同的策略的对象上。

i already know of this setImmediate (afaik, only newer IE) and WebWorkers(not yet in IE), but i just want to know if it's possible to just use the same strategy on an object.

推荐答案

有是属性没有异步功能的迭代器,因为没有办法救你是在比其他迭代器,其中的状态对于(OBJ中键)循环,你已经知道,是不是异步兼容。

There is no async-capable iterator of properties because there's no way to save the state of where you are in the iterator other than the for (key in obj) loop and you already know that isn't async-compatible.

所以,仅仅收取对象的所有键到一个数组,并使用你已经遍历键的排列在同一机制。阵列的优势在于他们有办法救你是在重复只需保持数组索引的赛道上的状况。

So, just collect all the keys of the object into an array and use the same mechanism you already have to iterate over the array of keys. Arrays have the advantage that they do have a way to save the state of where you are in the iteration by just keeping track of the array index.

一个可以得到所有的钥匙,无论是与 Object.keys(OBJ)(如果需要通过内置方法或ES5垫片)ES5方法或者你可以收集他们自己,如果你不以其他方式使用ES​​5垫片:

One can get all the keys, either with the Object.keys(obj) ES5 method (via built-in methods or ES5 shim if needed) or you can collect them yourself if you aren't otherwise using ES5 shims:

var keys = [];
for (var i in obj) {
    if (obj.hasOwnProperty(i)) {
        keys.push(i);
    }
}

这篇关于&QUOT;异步&QUOT;遍历在JavaScript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆