Last active
November 9, 2016 15:38
-
-
Save eschwartz/af1634a9028d58a405e4a29851a97c33 to your computer and use it in GitHub Desktop.
Run a series of async batch jobs
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
/** | |
* Run a series of async functions in "batches", | |
* so that `batchSize` number of fns are running concurrently | |
* | |
* @param {function():Promise<T>[]} fns | |
* @param {int} batchSize | |
* @return {Promise<T[]>} | |
*/ | |
function batch(fns, batchSize) { | |
const batchFns = _.chunk(fns, batchSize) | |
.map(fnsInBatch => | |
() => Promise.all(fnsInBatch.map(fn => fn())) | |
); | |
// https://gist.github.com/eschwartz/565e92418d903b7e98dd7bb9679293c1 | |
return sequence(batchFns) | |
// flatten | |
.then(batchResults => batchResults.reduce((resList, res) => resList.concat(res), [])) | |
} |
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
import sequence from './sequence'; | |
import {IAsyncFn} from './sequence'; | |
/** | |
* Run a series of async functions in "batches", | |
* so that `batchSize` number of fns are running concurrently | |
*/ | |
function batch<TRes>(fns:IAsyncFn<TRes>[], batchSize:number):Promise<TRes[]> { | |
const batchFns = chunk<IAsyncFn<TRes>>(fns, batchSize) | |
.map(fnsInBatch => | |
() => Promise.all(fnsInBatch.map(fn => fn())) | |
); | |
return sequence<TRes[]>(batchFns) | |
// flatten | |
.then(batchResults => batchResults.reduce((resList, res) => resList.concat(res), [])) | |
} | |
function chunk<TVal>(list:TVal[], chunkSize:number):TVal[][] { | |
return list.reduce((chunks, item, i) => { | |
const chunkNumber = Math.floor(i / chunkSize); | |
chunks[chunkNumber] || (chunks[chunkNumber] = []); | |
chunks[chunkNumber].push(item); | |
return chunks; | |
}, []) | |
} | |
export default batch; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
eg
Note that it ran
A
andB
in parallel, and waiting for them to complete for runningC
andD