I have several scenarios in my code that fit this pattern, and I'm sure its a common programming issue. I want to loop through an array or an object, and run a (potentially) asynchronous function on each iteration. I do not want the next iteration to start until the current one has finished.
Here's the code that would work if the processing was synchronous
var k;
for (k in data) {
var thisdata = data[k];
dosomething(thisdata);
}
In the above, dosomething might visit the server, or it might throw up a dialog box for user input, or it might just do some local processing in js.
Here's the solution I've come up with:
var keys = Object.keys(data);
var index = 0;
exec();
function exec() {
if (index == keys.length) return;
var k = keys[index++];
var thisdata = data[k];
dosomething(thisdata, exec);
}
So dosomething() had to be modified to take a callback, which is fine, but using Object.keys and having such inelegant and difficult to read code seems wrong. So is there an easier/better way ?
Also there could potentially be thousands of iterations of this loop, so "stackoverflow" is a concern, I suppose, ie. having a 1000 deep recursion going on.