Skip to content

Instantly share code, notes, and snippets.

@Pamblam
Last active March 2, 2018 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pamblam/61a636dd02a8dc43fa6c01f667a05a64 to your computer and use it in GitHub Desktop.
Save Pamblam/61a636dd02a8dc43fa6c01f667a05a64 to your computer and use it in GitHub Desktop.
Run an asynchronous operation on each item in an array, waiting for the previous iteration to complete before doing the next one
/**
* Execute the loopBody function once for each item in the items array,
* waiting for the done function (which is passed into the loopBody function)
* to be called before proceeding to the next item in the array.
* @param {Array} items - The array of items to iterate through
* @param {Function} loopBody - A function to execute on each item in the array.
* This function is passed 3 arguments -
* 1. The item in the current iteration,
* 2. The index of the item in the array,
* 3. A function to be called when the iteration may continue.
* @returns {Promise} - A promise that is resolved when all the items in the
* in the array have been iterated through.
*/
function slowLoop(items, loopBody) {
return new Promise(f => {
let done = arguments[2] || f;
let idx = arguments[3] || 0;
let cb = items[idx + 1] ? () => slowLoop(items, loopBody, done, idx + 1) : done;
loopBody(items[idx], idx, cb);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment