Last active
March 5, 2017 14:35
-
-
Save jpsecher/09fb8b982cb70ed4226a09c2d7f5972c to your computer and use it in GitHub Desktop.
Promise sequence with delay & progress
This file contains hidden or 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
'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