Last active
March 2, 2018 13:59
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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