Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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