UNPKG

rubico

Version:

[a]synchronous functional programming

36 lines (33 loc) 1.09 kB
const isPromise = require('./isPromise') const promiseAll = require('./promiseAll') const always = require('./always') /** * @name asyncGeneratorFunctionForEach * * @synopsis * ```coffeescript [specscript] * var T any, * asyncGeneratorFunction ...args=>AsyncGenerator<T>, * callback T=>() * * asyncGeneratorFunctionForEach(asyncGeneratorFunction, callback) -> ...args=>Promise<AsyncGenerator<>> * ``` * * @description * Create an async generator executor that executes a callback for each item of an async generator generated by an async generator function. */ const asyncGeneratorFunctionForEach = ( asyncGeneratorFunction, callback, ) => async function* executingCallbackForEach(...args) { const promises = [], asyncIterator = asyncGeneratorFunction(...args) for await (const item of asyncIterator) { const operation = callback(item) if (isPromise(operation)) { promises.push(operation) } } return promises.length == 0 ? asyncIterator : promiseAll(promises).then(always(asyncIterator)) } module.exports = asyncGeneratorFunctionForEach