“Async” loop over an object in javascript

2019-04-12 06:16发布

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

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.

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.

1条回答
We Are One
2楼-- · 2019-04-12 06:38

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.

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);
    }
}
查看更多
登录 后发表回答