Created
February 23, 2016 15:47
-
-
Save eschwartz/ccaafc20efd19a89700e to your computer and use it in GitHub Desktop.
Promise Series: run an async fn in series an arbitrary number of times
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
const _ = require('lodash'); | |
function series(count, asyncFn) { | |
return _.range(0, count) | |
.reduce((lastRun_, i) => { | |
return lastRun_.then(() => asyncFn(i)) | |
}, Promise.resolve()); | |
} | |
series(10, (i) => { | |
console.log(i); | |
return new Promise(resolve => setTimeout(resolve, 500)) | |
}) | |
.then(() => console.log('done'), err => console.error(err)); |
Or...
function clearTicks(tickCount) {
return _.range(0, tickCount)
.reduce(lastTick_ => {
return lastTick_.then(new Promise(process.nextTick))
}, Promise.resolve());
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm using this to "clear out"
process.nextTick
in tests