Skip to content

Instantly share code, notes, and snippets.

@karataev
Created September 25, 2019 16:16
Show Gist options
  • Save karataev/b79455db0d6adb651a9fd687a29eb1af to your computer and use it in GitHub Desktop.
Save karataev/b79455db0d6adb651a9fd687a29eb1af to your computer and use it in GitHub Desktop.
Promise patterns
const _ = require('lodash');
function series(arr, fn) {
let result = [];
return _.reduce(arr, (acc, item) => {
acc = acc
.then(() => fn(item))
.then(res => result.push(res));
return acc;
}, Promise.resolve())
.then(() => result);
}
function all(arr, fn) {
let promises = _.map(arr, item => fn(item));
return Promise.all(promises)
}
function chunks(arr, fn, chunkSize) {
let result = [];
return _.chain(arr)
.chunk(chunkSize)
.reduce((acc, chunk) => {
acc = acc
.then(() => all(chunk, fn))
.then(res => result = result.concat(res));
return acc;
}, Promise.resolve())
.value()
.then(() => result);
}
module.exports = {
series,
all,
chunks
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment