Skip to content

Instantly share code, notes, and snippets.

@feeela
Last active December 4, 2023 16:20
Show Gist options
  • Save feeela/a97ebb529d7ed0561114 to your computer and use it in GitHub Desktop.
Save feeela/a97ebb529d7ed0561114 to your computer and use it in GitHub Desktop.
Recursive JS promises with delay
#!/usr/bin/nodejs
var Promise = require( 'promise' );
/**
*
* @param {Array} list
* @param {int} delay
*/
function recursivePromiseWithDelay( list, delay ) {
console.log( 'Return new promise' );
return new Promise( function( resolve, reject ) {
/* Get first list item */
var listItem = list.shift();
console.log( 'Set delay of ' + delay + ' seconds' );
setTimeout( function() {
/* Fake asynchronous operation,
* place an AJAX call or whatever here
*/
console.log( 'Start asynchronous operation "' + listItem + '"' );
setTimeout( function() {
console.log( 'Async operation "' + listItem + '" finished' );
if( list.length > 0 ) {
recursivePromiseWithDelay( list, delay ).then( function() {
resolve();
});
}
else {
resolve();
}
}, 2345 );
/* End of async operation */
}, delay * 1000 );
} );
}
recursivePromiseWithDelay( ['A', 'B', 'C', 'D', 'E'], 2 ).then( function( value ) {
console.log( 'Finished');
} ).catch( function( error ) {
console.error( error );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment