Last active

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Synchronous for loop in JavaScript to ensure that the n+1th item isn't processed until the callback of the nth item's processor has been called.

View doSynchronousLoop.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/**
* Process an array of data synchronously.
*
* @param data An array of data.
* @param processData A function that processes an item of data.
* Signature: function(item, i, callback), where {@code item} is the i'th item,
* {@code i} is the loop index value and {@code calback} is the
* parameterless function to call on completion of processing an item.
*/
function doSynchronousLoop(data, processData, done) {
if (data.length > 0) {
var loop = function(data, i, processData, done) {
processData(data[i], i, function() {
if (++i < data.length) {
loop(data, i, processData, done);
} else {
done();
}
});
};
loop(data, 0, processData, done);
} else {
done();
}
}

This was just a learning exercise for me and I posted it here for myself, but I made it public because there's no reason to hide it.

i love this <3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.