Skip to content

Instantly share code, notes, and snippets.

@eschwartz
Created February 23, 2016 15:47
Show Gist options
  • Save eschwartz/ccaafc20efd19a89700e to your computer and use it in GitHub Desktop.
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
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));
@eschwartz
Copy link
Author

I'm using this to "clear out" process.nextTick in tests

function clearTicks(tickCount) {
  return series(tickCount, () => new Promise(resolve => process.nextTick(resolve)));
}

@eschwartz
Copy link
Author

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