Options
All
  • Public
  • Public/Protected
  • All
Menu

Type parameters

  • A

Hierarchy

Implements

Index

Constructors

constructor

Properties

Protected Optional _cancelable

_cancelable: ICancelable

Reference to the current ICancelable available for subsequent data transformations.

Protected, because it shouldn't be public API, being meant for Future implementations.

Protected _scheduler

_scheduler: Scheduler

Methods

ap

  • Applicative apply operator.

    Resembles map, but the passed mapping function is lifted in the Either context.

    Type parameters

    • B

    Parameters

    Returns Future<B>

attempt

  • attempt(): Future<Either<Throwable, A>>
  • Exposes underlying errors by lifting both successful and failed results into an Either value.

    Given that errors are short-circuiting the processing of flatMap chains, this method is useful for exposing errors such that you can flatMap over them.

    const f: Future<number> = Future.raise(new DummyError)
    
    // Yields a successful Left(DummyError) on completion
    const fe: Future<Either<Throwable, number>> = f.attempt()
    
    // Yields a Right(1) on completion
    const fr: Future<Either<Throwable, number>> = Future.pure(1).attempt()
    

    Returns Future<Either<Throwable, A>>

cancel

  • cancel(): void

chain

  • chain<B>(f: function): Future<B>

delayResult

  • Delays signaling the result of this Future by the specified duration.

    It works for successful results:

    const fa = Future.of(() => "Alex")
    
    // Delays the signaling by 1 second
    fa.delayResult(1000).flatMap
    

    And for failures as well:

    Future.raise(new TimeoutError()).delayResult(1000)
    

    Parameters

    • delay: number | Duration

      is the duration to wait before signaling the final result

    Returns Future<A>

flatMap

  • flatMap<B>(f: function): Future<B>
  • Chains asynchronous operations.

    Creates a new future by applying a function to the successful result of the source and returns the result of the function as the new future. If this future is completed with an exception then the new future will also contain this exception.

    This operation is the monadic bind (e.g. Monad.flatMap).

    const fa = Future.of(() => 3)
    const fb = Future.of(() => 5)
    
    // Yields 3 + 5
    fa.flatMap(a => fb.map(b => a + b))
    

    Type parameters

    • B

    Parameters

    • f: function

    Returns Future<B>

forEach

  • forEach(f: function): void
  • Asynchronously processes the value in the future once the value becomes available.

    WARNING: Will not be called if this future is never completed or if it is completed with a failure.

    Parameters

    • f: function

      the function which will be executed if this Future completes with a result

        • (a: A): void
        • Parameters

          • a: A

          Returns void

    Returns void

map

  • map<B>(f: function): Future<B>
  • Given a mapping function, transforms the successful result of the source.

    If the source is completed with an exception, then the new future will also be completed in an error.

    This operation is the functor map (e.g. Functor.map).

    const f = Future.of(() => "The future")
    
    const g = f.map(x => x + " is now!")
    

    Type parameters

    • B

    Parameters

    • f: function
        • (a: A): B
        • Parameters

          • a: A

          Returns B

    Returns Future<B>

onComplete

  • onComplete(f: function): void

recover

  • recover<AA>(f: function): Future<A | AA>
  • Creates a new future that will handle any matching throwable that this future might contain by assigning it a value.

    This operation is the equivalent of map for handling errors. Also see transform, which can handle both successful results and failures.

    const f = Future.of<number>(() => { throw new DummyError() })
    
    f.recover(e => {
      if (e instanceof DummyError) return 10
      // Don't re-throw exceptions like this, use `recoverWith` instead!
      throw e
    })
    

    Type parameters

    • AA

    Parameters

    • f: function
        • (e: Throwable): AA
        • Parameters

          • e: Throwable

          Returns AA

    Returns Future<A | AA>

recoverWith

  • recoverWith<AA>(f: function): Future<A | AA>
  • Creates a new future that will handle any matching throwable that this future might contain by assigning it a value of another future.

    This operation is the equivalent of flatMap for handling errors. Also see transformWith, which can handle both successful results and failures.

    const f = Future.of<number>(() => { throw new DummyError() })
    
    f.recoverWith(e => e instanceof DummyError
      ? Future.pure(10) // Fallback
      : Future.raise(e) // Re-throw
    )
    

    Type parameters

    • AA

    Parameters

    • f: function
        • Parameters

          • e: Throwable

          Returns Future<AA>

    Returns Future<A | AA>

then

  • then<TResult1, TResult2>(onFulfilled?: function | undefined | null, onRejected?: function | undefined | null): Future<TResult2 | TResult1>
  • JavaScript Thenable implementation, needed in order to await Future values in async functions.

    Type parameters

    • TResult1

    • TResult2

    Parameters

    • Optional onFulfilled: function | undefined | null
    • Optional onRejected: function | undefined | null

    Returns Future<TResult2 | TResult1>

timeout

  • Returns a future that mirrors the source in case the result of the source is signaled within the required after duration, otherwise it fails with a TimeoutError, cancelling the source.

    const fa = Future.of(() => 1).delayResult(10000)
    
    // Will fail with a TimeoutError
    fa.timeout(1000)
    

    Parameters

    • after: number | Duration

      is the duration to wait until it triggers the timeout error

    Returns Future<A>

timeoutTo

  • timeoutTo<AA>(after: number | Duration, fallback: function): Future<A | AA>
  • Returns a future that mirrors the source in case the result of the source is signaled within the required after duration, otherwise it triggers the execution of the given fallback after the duration has passed, cancelling the source.

    This is literally the implementation of Future.timeout:

    const fa = Future.of(() => 1).delayResult(10000)
    
    fa.timeoutTo(1000, () => Future.raise(new TimeoutError()))
    

    Type parameters

    • AA

    Parameters

    • after: number | Duration

      is the duration to wait until it triggers the fallback

    • fallback: function

      is a thunk generating a fallback Future to timeout to

    Returns Future<A | AA>

toPromise

  • toPromise(): Promise<A>

transform

  • transform<B>(failure: function, success: function): Future<B>
  • Transforms the sources, regardless if the result is a failure or a success.

    This function is a combination of map and recover, being the (type safe) alternative to JavaScript's then from the Promises/A+ specification.

    Example:

    import { Left, Right } from "funfix"
    
    // Expose errors by lifting them to an Either<Error, A>
    future.transform<Either<Throwable, A>>(Left, Right)
    

    Also see transformWith.

    Type parameters

    • B

    Parameters

    • failure: function

      is the function that's going to get executed in case the source signals a failure

        • (e: Throwable): B
        • Parameters

          • e: Throwable

          Returns B

    • success: function

      is the function that's going to get executed in case the source signals a successful result

        • (a: A): B
        • Parameters

          • a: A

          Returns B

    Returns Future<B>

transformWith

  • transformWith<B>(failure: function, success: function): Future<B>

value

  • value(): Option<Try<A>>

withScheduler

Static create

  • Given a side-effectful function that triggers an asynchronous computation, execute it and return a Future reference.

    The given register function will be invoked immediately to "schedule" the asynchronous callback, where the callback is the parameter injected in that function.

    The register function can optionally return a ICancelable reference that can get used to cancel the running asynchronous computation.

    Example:

    import { Scheduler, Future, Try, Duration, Cancelable } from "funfix"
    
    const delay = <A>(d: Duration, f: () => A, ec: Scheduler = Scheduler.global.get()) =>
      Future.create<A>(
        cb => {
          const task = ec.scheduleOnce(d, () => cb(Try.of(f)))
    
          return Cancelable.of(() => {
            console.warn("Delayed task was cancelled")
            task.cancel()
          })
        },
        ec
      )
    

    Note that by not returning a cancelable, the returned Future reference will NOT BE cancelable.

    // This future is not cancelable, because we are not
    // returning a cancelable reference
    Future.create<number>(cb => {
      setTimeout(1000, () => cb(Success(10)))
    })
    

    Type parameters

    • A

    Parameters

    • register: function

      is the side-effectful function that will get invoked to build our Future, receiving a callback that's supposed to get invoked (only once) when the asynchronous computation completes, and that can optionally return a cancelable reference that can get used to cancel the running computation

        • Parameters

          • cb: function
              • (a: Try<A>): void
              • Parameters

                • a: Try<A>

                Returns void

          Returns void | ICancelable

    • Default value ec: Scheduler = Scheduler.global.get()

      is an optional Scheduler reference that will get used for scheduling the actual async execution; if one isn't provided then Scheduler.global gets used, which also allows for local overrides, being a DynamicRef

    Returns Future<A>

Static delayedTick

  • Returns a Future that will complete after the given delay.

    This can be used to do delayed execution. For example:

    Future.delayedTick(1000).flatMap(_ =>
      Future.of(() => console.info("Hello!"))
    )
    

    Type parameters

    • A

    Parameters

    • delay: number | Duration

      is the duration to wait before signaling the tick

    • Default value ec: Scheduler = Scheduler.global.get()

      is the scheduler that will actually schedule the tick's execution

    Returns Future<void>

Static firstCompletedOf

  • Creates a race condition between multiple futures, returning the result of the first one that completes, cancelling the rest.

    const failure = Future.raise(new TimeoutError()).delayResult(2000)
    
    // Will yield 1
    const fa1 = Future.of(() => 1).delayResult(1000)
    Future.firstCompletedOf([fa1, failure])
    
    // Will yield a TimeoutError
    const fa2 = Future.of(() => 1).delayResult(10000)
    Future.firstCompletedOf([fa2, failure])
    

    Type parameters

    • A

    Parameters

    • list: Future<A>[] | Iterable<Future<A>>

      is the list of futures for which the race is started

    • Default value ec: Scheduler = Scheduler.global.get()

      is the scheduler doing the needed scheduling and error reporting

    Returns Future<A>

    a future that will complete with the result of the first future form the list to complete, the rest being cancelled

Static fromPromise

  • Transforms any Promise-like data type into a Future.

    const p: Promise<number> = Promise.resolve(10)
    
    const f: Future<number> = Future.fromPromise(p)
    

    Type parameters

    • A

    Parameters

    • ref: IPromiseLike<A>

      is the promise reference that we want to convert into a Future

    • Default value ec: Scheduler = Scheduler.global.get()

      is an optional Scheduler reference that will get used for scheduling the actual async execution; if one isn't provided then Scheduler.global gets used, which also allows for local overrides, being a DynamicRef

    Returns Future<A>

Static fromTry

  • Builds an already complete Future from a Try value.

    import { Success, Failure, Future } from "funfix"
    
    // Already completed with 1
    const f1 = Future.fromTry(Success(1))
    
    // Already completed in error
    const f2 = Future.fromTry(Failure("err"))
    

    Type parameters

    • A

    Parameters

    • value: Try<A>

      is the Try value to stream in onComplete listeners

    • Default value ec: Scheduler = Scheduler.global.get()

      is an optional Scheduler reference that will get used for scheduling the actual async execution; if one isn't provided then Scheduler.global gets used, which also allows for local overrides, being a DynamicRef

    Returns Future<A>

Static map2

  • Maps 2 Future values by the mapping function, returning a new Future reference that completes with the result of mapping that function to the successful values of the futures, or in failure in case either of them fails.

    This is a specialized Future.sequence operation and as such on cancellation or failure all future values get cancelled.

    const fa1 = Future.of(() => 1)
    const fa2 = Future.of(() => 2)
    
    
    // Yields Success(3)
    Future.map2(fa1, fa2, (a, b) => a + b)
    
    // Yields Failure, because the second arg is a Failure
    Future.map2(fa1, Future.raise("error"),
      (a, b) => a + b
    )
    

    This operation is the Applicative.map2.

    Type parameters

    • A1

    • A2

    • R

    Parameters

    • fa1: Future<A1>
    • fa2: Future<A2>
    • f: function
        • (a1: A1, a2: A2): R
        • Parameters

          • a1: A1
          • a2: A2

          Returns R

    • Default value ec: Scheduler = Scheduler.global.get()

    Returns Future<R>

Static map3

  • Maps 3 Future values by the mapping function, returning a new Future reference that completes with the result of mapping that function to the successful values of the futures, or in failure in case either of them fails.

    This is a specialized Future.sequence operation and as such on cancellation or failure all future values get cancelled.

    const fa1 = Future.of(() => 1)
    const fa2 = Future.of(() => 2)
    const fa3 = Future.of(() => 3)
    
    
    // Yields Success(6)
    Future.map3(fa1, fa2, fa3, (a, b, c) => a + b + c)
    
    // Yields Failure, because the second arg is a Failure
    Future.map3(
      fa1, fa2, Future.raise("error"),
      (a, b, c) => a + b + c
    )
    

    This operation is the Applicative.map3.

    Type parameters

    • A1

    • A2

    • A3

    • R

    Parameters

    • fa1: Future<A1>
    • fa2: Future<A2>
    • fa3: Future<A3>
    • f: function
        • (a1: A1, a2: A2, a3: A3): R
        • Parameters

          • a1: A1
          • a2: A2
          • a3: A3

          Returns R

    • Default value ec: Scheduler = Scheduler.global.get()

    Returns Future<R>

Static map4

  • Maps 4 Future values by the mapping function, returning a new Future reference that completes with the result of mapping that function to the successful values of the futures, or in failure in case either of them fails.

    This is a specialized Future.sequence operation and as such on cancellation or failure all future values get cancelled.

    const fa1 = Future.of(() => 1)
    const fa2 = Future.of(() => 2)
    const fa3 = Future.of(() => 3)
    const fa4 = Future.of(() => 4)
    
    // Yields Success(10)
    Future.map4(fa1, fa2, fa3, fa4, (a, b, c, d) => a + b + c + d)
    
    // Yields Failure, because the second arg is a Failure
    Future.map4(
      fa1, fa2, fa3, Future.raise("error"),
      (a, b, c, d) => a + b + c + d
    )
    

    This operation is the Applicative.map4.

    Type parameters

    • A1

    • A2

    • A3

    • A4

    • R

    Parameters

    • fa1: Future<A1>
    • fa2: Future<A2>
    • fa3: Future<A3>
    • fa4: Future<A4>
    • f: function
        • (a1: A1, a2: A2, a3: A3, a4: A4): R
        • Parameters

          • a1: A1
          • a2: A2
          • a3: A3
          • a4: A4

          Returns R

    • Default value ec: Scheduler = Scheduler.global.get()

    Returns Future<R>

Static map5

  • Maps 5 Future values by the mapping function, returning a new Future reference that completes with the result of mapping that function to the successful values of the futures, or in failure in case either of them fails.

    This is a specialized Future.sequence operation and as such on cancellation or failure all future values get cancelled.

    const fa1 = Future.of(() => 1)
    const fa2 = Future.of(() => 2)
    const fa3 = Future.of(() => 3)
    const fa4 = Future.of(() => 4)
    const fa5 = Future.of(() => 5)
    
    // Yields Success(15)
    Future.map5(fa1, fa2, fa3, fa4, fa5,
      (a, b, c, d, e) => a + b + c + d + e
    )
    
    // Yields Failure, because the second arg is a Failure
    Future.map5(
      fa1, fa2, fa3, fa4, Future.raise("error"),
      (a, b, c, d, e) => a + b + c + d + e
    )
    

    This operation is the Applicative.map5.

    Type parameters

    • A1

    • A2

    • A3

    • A4

    • A5

    • R

    Parameters

    • fa1: Future<A1>
    • fa2: Future<A2>
    • fa3: Future<A3>
    • fa4: Future<A4>
    • fa5: Future<A5>
    • f: function
        • (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5): R
        • Parameters

          • a1: A1
          • a2: A2
          • a3: A3
          • a4: A4
          • a5: A5

          Returns R

    • Default value ec: Scheduler = Scheduler.global.get()

    Returns Future<R>

Static map6

  • Maps 6 Future values by the mapping function, returning a new Future reference that completes with the result of mapping that function to the successful values of the futures, or in failure in case either of them fails.

    This is a specialized Future.sequence operation and as such on cancellation or failure all future values get cancelled.

    const fa1 = Future.of(() => 1)
    const fa2 = Future.of(() => 2)
    const fa3 = Future.of(() => 3)
    const fa4 = Future.of(() => 4)
    const fa5 = Future.of(() => 5)
    const fa6 = Future.of(() => 6)
    
    // Yields Success(21)
    Future.map6(
      fa1, fa2, fa3, fa4, fa5, fa6,
      (a, b, c, d, e, f) => a + b + c + d + e + f
    )
    
    // Yields Failure, because the second arg is a Failure
    Future.map6(
      fa1, fa2, fa3, fa4, fa5, Future.raise("error"),
      (a, b, c, d, e, f) => a + b + c + d + e + f
    )
    

    This operation is the Applicative.map6.

    Type parameters

    • A1

    • A2

    • A3

    • A4

    • A5

    • A6

    • R

    Parameters

    • fa1: Future<A1>
    • fa2: Future<A2>
    • fa3: Future<A3>
    • fa4: Future<A4>
    • fa5: Future<A5>
    • fa6: Future<A6>
    • f: function
        • (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6): R
        • Parameters

          • a1: A1
          • a2: A2
          • a3: A3
          • a4: A4
          • a5: A5
          • a6: A6

          Returns R

    • Default value ec: Scheduler = Scheduler.global.get()

    Returns Future<R>

Static of

  • Given a function that executes immediately, executes it asynchronously and returns a Future that will complete when the result is ready.

    const sum = (x: number, y: number) =>
      Future.of(() => x + y)
    

    Type parameters

    • A

    Parameters

    • thunk: function

      is the function to execute asynchronously

        • (): A
        • Returns A

    • Default value ec: Scheduler = Scheduler.global.get()

      is an optional Scheduler reference that will get used for scheduling the actual async execution; if one isn't provided then Scheduler.global gets used, which also allows for local overrides, being a DynamicRef

    Returns Future<A>

Static pure

  • Lifts a pure value into the Future context, returning a Future reference that's already complete with the given value.

    This is the equivalent of Promise.resolve(a).

    const f: Future<number> = Future.pure(10)
    
    // Prints Success(10)
    f.onComplete(r => console.info(r))
    

    Type parameters

    • A

    Parameters

    • a: A

      is the value to lift in the Future context and that will get signaled in onComplete callbacks

    • Default value ec: Scheduler = Scheduler.global.get()

      is an optional Scheduler reference that will get used for scheduling the actual async execution; if one isn't provided then Scheduler.global gets used, which also allows for local overrides, being a DynamicRef

    Returns Future<A>

Static raise

  • Lifts an error in the Future context, returning a Future reference that's already failed with the given error.

    This is the equivalent of Promise.reject.

    const f: Future<number> = Future.raise("Oops!")
    
    // Prints Failure("Oops!")
    f.onComplete(r => console.info(r))
    

    Type parameters

    • A

    Parameters

    • e: Throwable

      is the error to lift in the Future context and that will get signaled as a failure in onComplete callbacks

    • Default value ec: Scheduler = Scheduler.global.get()

      is an optional Scheduler reference that will get used for scheduling the actual async execution; if one isn't provided then Scheduler.global gets used, which also allows for local overrides, being a DynamicRef

    Returns Future<A>

Static sequence

  • Asynchronously transforms a list of futures into a future of a list.

    The equivalent of Promise.all, this is the specialized version of Future.traverse.

    Contract:

    • the given Iterable<Future<A>> list is eagerly evaluated, transformed from the start into an Array<Future<A>>, so don't expect laziness in evaluating it
    • In case one of the future fails, then all other futures that are still pending get cancelled
    • In case the returned future gets cancelled, then all in-progress futures from that list get cancelled

    Sample:

    const f1 = Future.of(() => 1)
    const f2 = Future.of(() => 2)
    const f3 = Future.of(() => 3)
    
    // Yields [1, 2, 3]
    const all: Future<number[]> = Future.sequence([f1, f2, f3])
    

    Type parameters

    • A

    Parameters

    Returns Future<A[]>

Static tailRecM

  • Keeps calling f until it returns a Right value.

    Based on Phil Freeman's Stack Safety for Free.

    const generate = () => {
      const n = Math.random() * 1000
      return n & n
    }
    
    // Keeps looping until an odd number is returned
    Future.tailRecM(0, a => Future.of(() => {
      return a % 2 == 0 ? Left(generate()) : Right(a)
    })
    

    Type parameters

    • A

    • B

    Parameters

    • a: A

      is the initial seed

    • f: function

      is the function that keeps being invoked with the previous Left(a) value, until a Right(b) value is returned, which will be the onComplete result of the Future reference

        • (a: A): Future<Either<A, B>>
        • Parameters

          • a: A

          Returns Future<Either<A, B>>

    • Default value ec: Scheduler = Scheduler.global.get()

      is an optional Scheduler reference that will get used for scheduling the actual async execution; if one isn't provided then Scheduler.global gets used, which also allows for local overrides, being a DynamicRef

    Returns Future<B>

Static traverse

  • traverse<A>(list: A[] | Iterable<A>, parallelism?: number, ec?: Scheduler): function
  • Given a list of items, builds future results out of it with the specified mapping function and returns a new future that's going to be completed with the list of all generated results.

    This is the generic version of Future.sequence. Useful for processing futures in parallel, with the parallelism factor being configurable.

    Example:

    const list = [1, 2, 3, 4]
    
    // Yields [2, 4, 6, 8]
    Future.traverse(list)(a => Future.pure(a * 2))
    // ... is equivalent to:
    Future.sequence(list.map(_ => _ * 2))
    

    Note that the given list is strictly processed, so no lazy behavior should be expected if an Iterable is given.

    But in comparison with Future.sequence, this builder has lazy behavior in applying the given mapping function. Coupled with the parallelism factor, this can be used to do batched processing:

    const userIDs = [1, 2, 3, 4]
    
    // Make at most 2 requests in parallel:
    Future.traverse(userIDs, 2)(fetchUserDetails)
    

    Type parameters

    • A

    Parameters

    • list: A[] | Iterable<A>

      are the values that get fed in the generator function for building a list of future results

    • Default value parallelism: number = Infinity

      is the maximum number of futures that are going to be processed in parallel, defaults to Infinity

    • Default value ec: Scheduler = Scheduler.global.get()

      is an optional scheduler that's going to be used for scheduling the needed asynchronous boundaries

    Returns function

    a function that takes as parameter a the generator function that's going to map the given list, transforming it into a list of futures, finally returning a future that's going to complete with the list of all asynchronously generated results

      • <B>(f: function): Future<B[]>
      • Type parameters

        • B

        Parameters

        • f: function

        Returns Future<B[]>

Static unit

  • Returns a Future reference that's already completed with a void value.

    Alias for:

    Future.pure(undefined)
    

    Note that the same reference is always returned, so this property holds:

    Future.unit() === Future.unit()
    

    Parameters

    • Default value ec: Scheduler = Scheduler.global.get()

    Returns Future<void>

Legend

  • Module
  • Object literal
  • Variable
  • Function
  • Function with type parameter
  • Index signature
  • Type alias
  • Enumeration
  • Enumeration member
  • Property
  • Method
  • Interface
  • Interface with type parameter
  • Constructor
  • Property
  • Method
  • Index signature
  • Class
  • Class with type parameter
  • Constructor
  • Property
  • Method
  • Accessor
  • Index signature
  • Inherited constructor
  • Inherited property
  • Inherited method
  • Inherited accessor
  • Protected property
  • Protected method
  • Protected accessor
  • Private property
  • Private method
  • Private accessor
  • Static property
  • Static method

Generated using TypeDoc