Last active
December 4, 2023 16:20
-
-
Save feeela/a97ebb529d7ed0561114 to your computer and use it in GitHub Desktop.
Recursive JS promises with delay
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
#!/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