piall
v0.2.1
Published
`Promise.all` and `Promise.allSettled` with concurrency option and async iterable result
Downloads
311,154
Maintainers
Readme
piall
Promise-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.
Install
$ yarn add piall
API
const piAll: <T>(iterable: Iterable<() => Promise<T> | T, concurrency?: number) => AsyncIterable<T>
type TFulfilled<T> = {
status: 'fulfilled',
value: T,
}
type TRejected = {
status: 'rejected',
reason: Error | string,
}
const piAllSettled: <T>(iterable: Iterable<() => Promise<T> | T, concurrency?: number) => AsyncIterable<TFulfilled<T> | TRejected>
where:
iterable
– any iterable of Promise/value factories like array, Set values, Map entries, etcconcurrency
– number >=1,Infinity
by default
Usage
export const pDelay = <T>(ms: number, value: T): Promise<T> => {
return new Promise((resolve) => {
setTimeout(() => resolve(value), ms)
})
}
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'
}
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' }
}
Thanks
To Artem Tyurin for a really nice trick with Promise.race
.