@b-jones-rfd/func-help - v0.7.1
    Preparing search index...

    Class AsyncIO<A>

    A lazy, composable description of an async side effect that runs only when run() is called.

    Keeping the effect unexecuted until run() lets a program be built from small pieces and kept referentially transparent; nothing happens at construction time.

    Every error, including a synchronous throw from the from effect or a throw in a caller-supplied function, rejects the promise run() returns; run() never throws.

    Haskell's IO already covers asynchronous work, so AsyncIO is this package's addition: it gives promise-returning effects their own type.

    import { AsyncIO } from '@b-jones-rfd/func-help'

    const fetchName = AsyncIO.from(() => Promise.resolve('Ada'))

    const greet = fetchName
    .map((name) => `Hello, ${name}`)
    .tap((greeting) => console.log(greeting))

    const greeting: string = await greet.run() // logs and returns 'Hello, Ada'

    Type Parameters

    • A

      The value the effect resolves to.

    Implements

    Index
    • Let yield* bind this AsyncIO inside a do block: yields this AsyncIO and returns the value the block is resumed with.

      It exists for yield*, not for spreading: [...asyncIO] is a one-element array holding this AsyncIO itself, and does not run it.

      Returns Generator<AsyncIO<A>, A, unknown>

      A generator that yields this AsyncIO once.

      import { AsyncIO } from '@b-jones-rfd/func-help'

      const n = await AsyncIO.do(function* () {
      const x = yield* AsyncIO.of(2) // calls this method
      return x * 2
      }).run() // 4
    • Capture a rejection as data: an AsyncIO that runs this one and resolves to an Except, ok holding the value or failed holding the error.

      A rejection or a synchronous throw anywhere in the chain built before attempt becomes a failed Except, so the promise run() returns for the result never rejects. A non-Error is wrapped as Except.tryCatch wraps it, with the original as cause. A function chained after attempt rejects run() as usual.

      This is Haskell's try (Control.Exception), renamed because try reads as the statement.

      Returns AsyncIO<Except<A>>

      An AsyncIO that resolves to ok holding this one's value, or failed holding the error it rejected with.

      import { AsyncIO } from '@b-jones-rfd/func-help'

      const fetchUser = AsyncIO.from(
      (): Promise<string> => Promise.reject(new Error('offline'))
      )

      const result = await fetchUser.attempt().run()
      const message = result.fold(
      (e) => `failed: ${e.message}`,
      (name) => name
      ) // 'failed: offline'
    • Sequence a further AsyncIO that depends on this one's resolved value.

      This is Haskell's >>=.

      If f throws, the promise returned by run() rejects with that error.

      Type Parameters

      • B

        The value the next step resolves to.

      Parameters

      • f: (a: A) => AsyncIO<B>

        The next step, given the resolved value.

      Returns AsyncIO<B>

      An AsyncIO that runs this effect, then the one f returns.

      import { AsyncIO } from '@b-jones-rfd/func-help'

      const userId = AsyncIO.of(7)
      const loadUser = (id: number) =>
      AsyncIO.from(() => Promise.resolve({ id, name: 'Ada' }))

      const user = await userId.bind(loadUser).run() // { id: 7, name: 'Ada' }
    • Transform the resolved value with a plain function.

      If f throws, the promise returned by run() rejects with that error.

      Type Parameters

      • B

        The type f returns.

      Parameters

      • f: (a: A) => B

        The function to apply to the resolved value.

      Returns AsyncIO<B>

      An AsyncIO that resolves to f of this one's value.

      import { AsyncIO } from '@b-jones-rfd/func-help'

      const length = AsyncIO.of('hello').map((s) => s.length)
      const n: number = await length.run() // 5
    • Perform the effect, and every effect composed into it, and resolve to the result.

      Any error, including one the effect throws before returning a promise, rejects the returned promise.

      Returns Promise<A>

      A promise of the effect's result.

      import { AsyncIO } from '@b-jones-rfd/func-help'

      const value: string = await AsyncIO.of('done').run() // 'done'
    • Run a synchronous side effect on the resolved value and pass the value on unchanged.

      If sideEffect throws, the promise returned by run() rejects with that error.

      Parameters

      • sideEffect: (a: A) => void

        The function to call with the resolved value.

      Returns AsyncIO<A>

      An AsyncIO that resolves to the same value as this one.

      import { AsyncIO } from '@b-jones-rfd/func-help'

      const logged = AsyncIO.of('ready').tap((s) => console.log(s))
      const s: string = await logged.run() // logs 'ready', returns 'ready'
    • Run every AsyncIO in an array at the same time, resolving to their results as an array in input order. An empty array gives [].

      A typed Promise.all: every item starts at once, the first rejection in time rejects the promise run() returns, and the others keep running (no cancellation) with their rejections observed. Nothing runs until run(), and every run() runs every item again. The array is copied when the AsyncIO is built.

      This is concurrently from Haskell's async package, with one departure: Haskell's takes two actions and returns a pair, and this one takes any number. A tuple gives a tuple: [AsyncIO<number>, AsyncIO<string>] gives AsyncIO<[number, string]>, with no as const. An array gives an array. Use sequence to run them one after another.

      Type Parameters

      • const T extends readonly AsyncIO<any>[]

        The array or tuple of AsyncIOs.

      Parameters

      • items: T

        The AsyncIOs.

      Returns AsyncIO<{ -readonly [K in string | number | symbol]: ValueOf<T[K]> }>

      An AsyncIO that resolves to the results in input order (a tuple for a tuple).

      import { AsyncIO } from '@b-jones-rfd/func-help'

      const [user, settings] = await AsyncIO.concurrently([
      AsyncIO.from(() => Promise.resolve({ name: 'Ada' })),
      AsyncIO.from(() => Promise.resolve({ theme: 'dark' })),
      ]).run()
      // user.name and settings.theme are typed
    • Build an AsyncIO from a do block: Haskell's do notation, with x <- m written const x = yield* m.

      The block is a plain generator function, not an async one: each yield* m waits for m and binds what it resolves to, typed with no annotation. Nothing in the block runs until run() is called, and every run() starts the block afresh. A throw in the block rejects the promise run() returns. A plain yield (without *) binds unknown; use yield*.

      Type Parameters

      • A

        The value the block returns.

      Parameters

      • block: () => Generator<AsyncIO<unknown>, A, unknown>

        A generator function that yield*s AsyncIOs and returns the result.

      Returns AsyncIO<A>

      An AsyncIO that runs the block and resolves to what it returns.

      import { AsyncIO } from '@b-jones-rfd/func-help'

      const loadUser = (id: number) =>
      AsyncIO.from(() => Promise.resolve({ id, name: 'Ada' }))

      const greeting = AsyncIO.do(function* () {
      const id = yield* AsyncIO.of(7) // number
      const user = yield* loadUser(id) // { id: number; name: string }
      return `Hello, ${user.name}`
      }) // AsyncIO<string>

      await greeting.run() // 'Hello, Ada'
    • Wrap a promise-returning side effect without running it.

      Taking a thunk rather than a promise is what keeps the effect lazy: a promise has already started by the time it exists.

      If effect throws synchronously or its promise rejects, the promise run() returns rejects with that error.

      Type Parameters

      • A

        The value effect resolves to.

      Parameters

      • effect: () => Promise<A>

        The async side effect to defer until run().

      Returns AsyncIO<A>

      An AsyncIO that calls effect each time it is run.

      import { AsyncIO } from '@b-jones-rfd/func-help'

      const now = AsyncIO.from(() => Promise.resolve(Date.now()))
      const ms: number = await now.run()
    • Lift an Except into AsyncIO: ok resolves to the value, and a failure rejects with its Error itself.

      Nothing in it calls caller code, so it never throws. If the ok value is a promise, it is awaited, as AsyncIO.of awaits one.

      This is Haskell's liftEither (MonadError), named after the package's from* constructors. There is no fromEither, because a Left need not be an Error: mapLeft it to an Error, then Except.fromEither, then fromExcept.

      Type Parameters

      • A

        The ok value type.

      Parameters

      • except: Except<A>

        The Except to lift.

      Returns AsyncIO<A>

      An AsyncIO that resolves to the ok value, or rejects with the error.

      import { AsyncIO, Except } from '@b-jones-rfd/func-help'

      const parsed = Except.ok(80)
      const n: number = await AsyncIO.fromExcept(parsed).run() // 80
      // AsyncIO.fromExcept(Except.failed(new Error('bad'))).run() rejects with that Error
    • Lift an IO into AsyncIO. The IO runs each time the AsyncIO runs, not when it is built.

      If the IO throws, the promise run() returns rejects with that error. If the IO produces a promise, it is awaited, as AsyncIO.of awaits one; the type still says AsyncIO<Promise<…>>, so lift an IO<Promise<A>> with AsyncIO.from(() => io.run()) instead.

      This is Haskell's liftIO, named after the package's from* constructors.

      Type Parameters

      • A

        The value the IO produces.

      Parameters

      • io: IO<A>

        The IO to run inside this one.

      Returns AsyncIO<A>

      An AsyncIO that runs io and resolves to its value.

      import { AsyncIO, IO } from '@b-jones-rfd/func-help'

      const port = IO.from(() => 8080)
      const n: number = await AsyncIO.fromIO(port).run() // 8080
    • An AsyncIO that applies f to every item and runs all the AsyncIOs it returns at the same time, resolving to the results as one array in input order (not the order they finish). An empty array gives [].

      Every item starts at once; there is no limit on how many run together. The first rejection in time rejects the promise run() returns, as with Promise.all. The other items keep running, because AsyncIO has no cancellation, and their rejections are observed, so none goes unhandled. A synchronous throw from f counts as that item's rejection, and f is still called for every item. Nothing runs, and f is not called, until run(); every run() runs every item again. The array is copied when the AsyncIO is built.

      This is mapConcurrently from Haskell's async package. Use traverse to run the items one after another.

      Type Parameters

      • T

        The item type.

      • A

        The value type of the AsyncIO f returns.

      Parameters

      • items: readonly T[]

        The items.

      • f: (item: T, index: number) => AsyncIO<A>

        Turns one item into an AsyncIO, given the item and its index.

      Returns AsyncIO<A[]>

      An AsyncIO that resolves to every result in input order.

      import { AsyncIO } from '@b-jones-rfd/func-help'

      const load = (id: number): AsyncIO<string> =>
      AsyncIO.from(() => Promise.resolve(`user ${id}`))

      const users: string[] = await AsyncIO.mapConcurrently([1, 2], load).run()
      // ['user 1', 'user 2'], loaded at the same time
    • Lift a plain value into AsyncIO without performing any effect.

      Named of rather than Haskell's pure / return, to match the other monads in this package.

      Type Parameters

      • A

        The type of value.

      Parameters

      • value: A

        The value the effect resolves to.

      Returns AsyncIO<A>

      An AsyncIO whose run() resolves to value.

      import { AsyncIO } from '@b-jones-rfd/func-help'

      const answer = AsyncIO.of(42)
      const n: number = await answer.run() // 42
    • Turn an array of AsyncIOs into one AsyncIO that runs them one after another and resolves to their results as an array. An empty array gives [].

      Each item starts only after the one before resolves; use concurrently to run them at the same time. Nothing runs until run(), and every run() runs every item again. The array is copied when the AsyncIO is built. The first rejection rejects the promise run() returns, and the items after it don't start.

      This is Haskell's sequence (Data.Traversable). A tuple gives a tuple: [AsyncIO<number>, AsyncIO<string>] gives AsyncIO<[number, string]>, with no as const. An array gives an array.

      Type Parameters

      • const T extends readonly AsyncIO<any>[]

        The array or tuple of AsyncIOs.

      Parameters

      • items: T

        The AsyncIOs, in order.

      Returns AsyncIO<{ -readonly [K in string | number | symbol]: ValueOf<T[K]> }>

      An AsyncIO that resolves to the results in input order (a tuple for a tuple).

      import { AsyncIO } from '@b-jones-rfd/func-help'

      const [host, port] = await AsyncIO.sequence([
      AsyncIO.of('localhost'),
      AsyncIO.from(() => Promise.resolve(8080)),
      ]).run()
      // host: string, port: number
    • An AsyncIO that applies f to each item and runs the AsyncIO it returns, one after another, and resolves to the results as one array. An empty array gives [].

      Each item starts only after the one before resolves; use mapConcurrently to run them at the same time. Nothing runs, and f is not called, until run(); every run() runs every item again. The array is copied when the AsyncIO is built. The first rejection, or a throw from f, rejects the promise run() returns, and the items after it don't start.

      This is Haskell's traverse (also mapM). Like Array#map, f also gets the item's index.

      Type Parameters

      • T

        The item type.

      • A

        The value type of the AsyncIO f returns.

      Parameters

      • items: readonly T[]

        The items, in order.

      • f: (item: T, index: number) => AsyncIO<A>

        Turns one item into an AsyncIO, given the item and its index.

      Returns AsyncIO<A[]>

      An AsyncIO that resolves to every result in input order.

      import { AsyncIO } from '@b-jones-rfd/func-help'

      const load = (id: number): AsyncIO<string> =>
      AsyncIO.from(() => Promise.resolve(`user ${id}`))

      const users: string[] = await AsyncIO.traverse([1, 2], load).run()
      // ['user 1', 'user 2'], loaded one after another