24

piall – "Promise.all"-like but provides concurrency option and returns...

 4 years ago
source link: https://github.com/nextools/metarepo/tree/master/packages/piall
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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, etc
  • concurrency – 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 .


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK