Created
September 25, 2019 16:16
-
-
Save karataev/b79455db0d6adb651a9fd687a29eb1af to your computer and use it in GitHub Desktop.
Promise patterns
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
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