feat(utils/asyncMap): better map + Promise.all (#543)

Because it waits for all promises to settle.
This commit is contained in:
Julien Fontanet
2017-05-11 17:34:41 +02:00
committed by GitHub
parent f361c22fce
commit 0d49361f50

View File

@@ -9,6 +9,7 @@ import isArray from 'lodash/isArray'
import isString from 'lodash/isString'
import keys from 'lodash/keys'
import kindOf from 'kindof'
import mapToArray from 'lodash/map'
import multiKeyHashInt from 'multikey-hash'
import pick from 'lodash/pick'
import tmp from 'tmp'
@@ -38,6 +39,30 @@ import {
// ===================================================================
// Similar to map() + Promise.all() but wait for all promises to
// settle before rejecting (with the first error)
export const asyncMap = (collection, iteratee) => {
let errorContainer
const onError = error => {
if (errorContainer === undefined) {
errorContainer = { error }
}
}
return Promise.all(mapToArray(collection, (item, key, collection) =>
new Promise(resolve => {
resolve(iteratee(item, key, collection))
}).catch(onError)
)).then(values => {
if (errorContainer !== undefined) {
throw errorContainer.error
}
return values
})
}
// -------------------------------------------------------------------
export function bufferToStream (buf) {
const stream = new Readable()