promises-pipes package includes a set of useful functions that simplify dealing with iterative promises.
npm i promises-pipes
const {series} = require('promises-pipes')
function promiseFunction(...args) {
return new Promise((resolve, reject) => {
setTimeout(function () {
resolve(args)
}, 100);
})
}
let promises = [
[promiseFunction, 'Hello','World'],
[promiseFunction, 1, 2, 3],
[promiseFunction]
]
series(promises)
.then(results => {
// results array
// [ [ 'Hello', 'World' ], [ 1, 2, 3 ], [] ]
})
.catch(err => {
throw err
})
Each method execute tasks in a different behavior, eather sequencial or parallel.
Task
A task is an array [promiseFunction, ...args]
, The first item of the array should be a function that returns a promise, and the rest of the items are the arguments that the function expects.
Excute tasks sequentially
series([tasks])
Excute task multiple times sequentially
seriesTimes(task, number)
Excute parallel tasks, does not guarantee the sequence of execution.
parallel([tasks])
Excute parallel tasks but limit the number of running tasks.
limitedParallel([tasks], limit, stopFunction)
Can be added to limitedParallel function, makes limitedParallel reject with error that is instance of StopPipe class and has the stopResponse which is the first result that met the stopFunction condition.
const {limitedParallel, StopPipe} = require('promises-pipes')
function stopFunction(result) {
return (condition)
}
limitedParallel([tasks], limit, stopFunction)
.then(result)
.catch(StopPipe => {
// StopPipe instance
})