📅 You're Invited: Meet the Socket team at RSAC (April 28 – May 1).RSVP
Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

delayed-loop

function to handle async looping

1.0.1
latest
64

Supply Chain Security

100

Vulnerability

72

Quality

75

Maintenance

100

License

Unpopular package

Quality

This package is not very popular.

Found 1 instance in 1 package

Version published
Weekly downloads
12
-20%
Maintainers
1
Weekly downloads
 
Created

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');
});

FAQs

Package last updated on 23 Aug 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts