Options
All
  • Public
  • Public/Protected
  • All
Menu

@marcelkloubert/promises

Index

Type aliases

DoRepeatAction<T, S>: ((context: DoRepeatActionContext<S>, ...args: any[]) => T) | ((context: DoRepeatActionContext<S>, ...args: any[]) => PromiseLike<T>) | Promise<T>

A possible value for action parameter of 'doRepeat()' function.

Type parameters

  • T = any

  • S = any

DoRepeatCondition<S>: (context: DoRepeatConditionContext<S>, ...args: any[]) => any

Type parameters

  • S = any

Type declaration

IsCanceledGetter: () => any

Type declaration

    • (): any
    • The getter for an 'isCanceled' prop of a 'CancelablePromise' instance.

      Returns any

PromiseCancelAction: (reason?: string) => any

Type declaration

    • (reason?: string): any
    • A 'cancel()' action for a 'CancelablePromise'.

      Parameters

      • Optional reason: string

      Returns any

PromiseQueueAction<T>: ((context: PromiseQueueActionContext, ...args: any[]) => T) | ((context: PromiseQueueActionContext, ...args: any[]) => PromiseLike<T>) | Promise<T>

An action for a 'PromiseQueue.enqueue()' call.

Type parameters

  • T = any

WaitForAction<T, S>: ((context: WaitForActionContext<S>, ...args: any[]) => T) | ((context: WaitForActionContext<S>, ...args: any[]) => PromiseLike<T>) | Promise<T>

A possible value for action parameter of 'waitFor()' function.

Type parameters

  • T = any

  • S = any

WaitForCondition<S>: (context: WaitForConditionContext<S>, ...args: any[]) => any

Type parameters

  • S = any

Type declaration

WithCancellationAction<T>: ((context: WithCancellationActionContext, ...args: any[]) => T) | ((context: WithCancellationActionContext, ...args: any[]) => PromiseLike<T>) | Promise<T>

A possible value for action parameter of 'withCancellation()' function.

Type parameters

  • T = any

WithRetriesAction<T>: ((...args: any[]) => T) | ((...args: any[]) => PromiseLike<T>) | Promise<T>

A possible value for action parameter of 'withRetries()' function.

Type parameters

  • T = any

WithTimeoutAction<T>: ((...args: any[]) => T) | ((...args: any[]) => PromiseLike<T>) | Promise<T>

A possible value for action parameter of 'withTimeout()' function.

Type parameters

  • T = any

Functions

  • Repeats an action or promise.

    example
    import assert from "assert"
    import { doRepeat, DoRepeatActionContext } from "@marcelkloubert/promises"

    const repeatCount = 5979
    const counter = 0

    const results = await doRepeat(async (context: DoRepeatActionContext) => {
    console.log("context.state", String(context.state))
    context.state = context.index * 2

    ++counter

    // do some work here
    }, repeatCount)

    assert.strictEqual(results.length, repeatCount)
    assert.strictEqual(counter, results.length)
    throws

    PartlyFailedErrorAt least one execution failed.

    
    

    Type parameters

    • T = any

    • S = any

    Parameters

    • action: DoRepeatAction<T, S>

      The action to invoke.

    • countOrCondition: number | DoRepeatCondition<any>

      The number of repeations or the condition.

    • Rest ...args: any[]

    Returns Promise<T[]>

    The promise with the list of all results.

  • isPromise(value: any): value is Promise<unknown>
  • Checks if a value is a Promise.

    example
    import { isPromise } from "@marcelkloubert/promises"
    import Bluebird from "bluebird"

    // all are (true)
    isPromise(Promise.resolve("Foo"))
    isPromise(Bluebird.resolve("Foo"))
    isPromise({
    then: (onfulfilled?: Function, onrejected?: Function): any => { },
    catch: (onrejected?: Function) => { },
    })

    // all are (false)
    isPromise("Foo")
    isPromise({
    then: (onfulfilled?: Function, onrejected?: Function): any => { },
    })
    isPromise(null)

    Parameters

    • value: any

      The value to check.

    Returns value is Promise<unknown>

    Is a Promise or not.

  • isPromiseLike(value: any): value is PromiseLike<unknown>
  • Checks if a value is a simple PromiseLike.

    example
    import { isPromiseLike } from "@marcelkloubert/promises"
    import Bluebird from "bluebird"

    // all are (true)
    isPromiseLike(Promise.resolve("Foo"))
    isPromiseLike(Bluebird.resolve("Foo"))
    isPromiseLike({
    then: (onfulfilled?: Function, onrejected?: Function): any => { },
    })

    // all are (false)
    isPromiseLike("Foo")
    isPromiseLike({ })
    isPromiseLike(null)

    Parameters

    • value: any

      The value to check.

    Returns value is PromiseLike<unknown>

    Is a PromiseLike or not.

  • Invokes an action or promise, but waits for a condition.

    example
    import { waitFor, WaitForActionContext, WaitForCondition } from "@marcelkloubert/promises"
    import fs from "fs"

    const waitForFile: WaitForCondition = async (context) => {
    // use context.cancel() function
    // to cancel the operation
    // maybe for a timeout

    // setup 'state' value for upcoming
    // action
    context.state = "Foo Bar BUZZ" // (s. below in action)

    // return a truthy value to keep waiting
    // otherwise falsy to start execution of action
    return !fs.existsSync("/path/to/my/file.xlsx")
    }

    const result = await waitFor(async ({ state }: WaitForActionContext) => {
    // state === "Foo Bar BUZZ" (s. above)
    }, waitForFile)

    Type parameters

    • T = any

    • S = any

    Parameters

    Returns Promise<T>

    The promise with the result of the action.

  • Invokes an action or promise, which can be cancelled.

    example
    import { CancellationError, withCancellation, WithCancellationActionContext } from "@marcelkloubert/promises"

    const promise = withCancellation(async (context: WithCancellationActionContext) => {
    let hasBeenFinished = false
    while (!context.cancellationRequested && !hasBeenFinished) {
    // do some long work here
    }
    })

    setTimeout(() => {
    promise.cancel("Promise action takes too long")
    }, 10000)

    try {
    await promise
    } catch (ex) {
    if (ex instanceof CancellationError) {
    // has been cancelled
    } else {
    // other error
    }
    }

    Type parameters

    • T

    Parameters

    Returns CancelablePromise<T>

    The new promise.

  • Invokes an action or promise and throws an error if a maximum number of tries has been reached.

    example
    import { MaximumTriesReachedError, withRetries } from "@marcelkloubert/promises"

    const myLongAction = async () => {
    // do something here
    }

    try {
    // try this action
    await withTimeout(myLongAction, {
    maxRetries: 9, // try invoke the myLongAction
    // with a maximum of 10 times
    // (first invocation + maxRetries)
    waitBeforeRetry: 10000, // wait 10 seconds, before retry
    })
    } catch (error) {
    // error should be a MaximumTriesReachedError instance
    console.error("Invokation of myLongAction failed", error)
    }
    throws

    MaximumTriesReachedError Action has run into a timeout.

    Type parameters

    • T = any

    Parameters

    Returns Promise<T>

    The result of the action.

  • Type parameters

    • T = any

    Parameters

    Returns Promise<T>

  • withTimeout<T>(action: WithTimeoutAction<T>, timeout: number, ...args: any[]): Promise<T>
  • Invokes an action or promise and throws an error on a timeout.

    example
    import { TimeoutError, withTimeout } from "@marcelkloubert/promises"

    const action = () => {
    return new Promise<string>((resolve) => {
    setTimeout(() => result("FOO"), 1000)
    })
    }

    // submit action as function
    // should NOT throw a TimeoutError
    const fooResult1 = await withTimeout(action, 10000)

    // submit action as Promise
    // this should throw a TimeoutError
    const fooResult2 = await withTimeout(action(), 100)
    throws

    TimeoutError Action has run into a timeout.

    Type parameters

    • T = any

    Parameters

    • action: WithTimeoutAction<T>

      The action to invoke.

    • timeout: number

      The maximum time in milliseconds.

    • Rest ...args: any[]

    Returns Promise<T>

    The result of the action.

  • Wraps the execution of a worker into a Promise.

    example
    import { withWorker } from "@marcelkloubert/promises"

    // this is code for Node.js
    // in a browser 'exitCode' will not exist
    const { exitCode, lastMessage } = await withWorker("/path/to/worker_script.js")

    Type parameters

    • T = any

    Parameters

    • workerFileOrUrl: string | URL

      The path to the script file or the URL.

    • options: WithWorkerOptions = {}

    Returns Promise<WithWorkerResult<T>>

    The promise with the result of the worker.

Generated using TypeDoc