delayed-loop
v1.0.1
Published
function to handle async looping
Downloads
45
Readme
Delayed Loop
A very simple function that iterates over an array asynchronously. Getting tired of copying this whole function out of my Github Gists so I'm publishing on NPM for convenience.
/**
* 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 delayedLoop(items, loopBody) {
return new Promise(f => {
let done = arguments[2] || f;
let idx = arguments[3] || 0;
let cb = items[idx + 1] ? () => delayedLoop(items, loopBody, done, idx + 1) : done;
loopBody(items[idx], idx, cb);
});
}
Usage
const dLoop = require('delayed-loop');
var arr = ['do','re','mi','fa','so','la','ti'];
const loop = dLoop(arr, (itm, idx, fin)=>{
// do something async,
// call fin() when ready to continue the loop
setTimeout(()=>{
console.log(`Item #${idx} is ${itm}`);
fin();
}, 1000);
});
// Promise resolves when all items have finished looping
loop.then(()=>{
console.log('done looping');
});