`Promise.all` and `Promise.allSettled` with concurrency option and async iterable result
npm install piallPromise-Iterable-All. Like Promise.all and Promise.allSettled but:
* takes Promise/value factories to invoke them lazily when needed
* returns "async iterable" to be consumed with for await...of
* iterates in whatever comes first order
* provides concurrency option
Consider using p-all if you need just Promise.all with concurrency option.
``sh`
$ yarn add piall
`ts`
const piAll:
`ts
type TFulfilled
status: 'fulfilled',
value: T,
}
type TRejected = {
status: 'rejected',
reason: Error | string,
}
const piAllSettled:
`
where:
* iterable – any iterable of Promise/value factories like array, Set values, Map entries, etcconcurrency
* – number >=1, Infinity by default
`ts`
export const pDelay =
return new Promise((resolve) => {
setTimeout(() => resolve(value), ms)
})
}
`ts
import { piAll } from 'piall'
import { pDelay } from './p-delay'
const asyncIterable = piAll([
() => pDelay(400, 'a'),
() => pDelay(100, 'b'),
() => pDelay(200, 'c'),
], 2)
for await (const result of asyncIterable) {
console.log(result)
// 'b'
// 'c'
// 'a'
}
`
`ts
import { piAllSettled } from 'piall'
import { pDelay } from './p-delay'
const asyncIterable = piAllSettled([
() => pDelay(300, 'a'),
() => pDelay(200, 'b'),
() => Promise.reject('oops'),
() => Promise.resolve('c'),
() => pDelay(200, 'd'),
], 3)
for await (const result of asyncIterable) {
console.log(result)
// { status: 'rejected', reason: 'oops' }
// { status: 'fulfilled', value: 'c' }
// { status: 'fulfilled', value: 'b' }
// { status: 'fulfilled', value: 'd' }
// { status: 'fulfilled', value: 'a' }
}
`
To Artem Tyurin for a really nice trick with Promise.race`.