Skip to content

Instantly share code, notes, and snippets.

@jpsecher
Last active March 5, 2017 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpsecher/09fb8b982cb70ed4226a09c2d7f5972c to your computer and use it in GitHub Desktop.
Save jpsecher/09fb8b982cb70ed4226a09c2d7f5972c to your computer and use it in GitHub Desktop.
Promise sequence with delay & progress
'use strict';
/**
* Dripwise process a list of items through a processing promise.
* @param {Array(α)} list Items to process.
* @param {int} msDelay Delay in ms between each processing.
* @param {α -> Promise(void)} processing Processer of one item.
* @param {int -> ()} progressReporter Optional function, called with index of item.
* @return {Promise(void)} Promise of the sequential processing.
*/
function sequenceWithDelay(list, msDelay, processing, progressReporter) {
return list.reduce((seq, item, index) => {
return seq.then(() => {
if (progressReporter) {
progressReporter(index);
}
return new Promise((resolve, reject) => {
processing(item)
.then(() => {
setTimeout(resolve, msDelay);
})
.catch(error => {
reject(error);
});
});
});
}, Promise.resolve());
}
sequenceWithDelay([1, 2, 3, 4, 5], 1000, item => {
return new Promise((resolve, reject) => {
console.log(`Processed ${item}`);
resolve();
});
}, index => {
if (index % 2 === 0) {
console.log(`Processing ${index}`);
}
})
.then(response => {
process.exit(0);
})
.catch(error => {
console.log(error);
process.exit(1);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment