3.1.1 • Published 3 years ago

tryfunc v3.1.1

Weekly downloads
91
License
ISC
Repository
github
Last release
3 years ago

tryfunc

NPM version Downloads Dependency status Dev Dependency status

tryCall: try invoking the function until it runs without throwing. Returns the value returned by the function.

tryUntil: try invoking the function until the returned value satisfies the provided validating function. Returns the value returned by the function.

Arguments:

  • func: the function to invoke with the iteration as a parameter
  • (only in tryUntil) validate: the validating function. Stops executing once the validator returns true.
  • Options object:
    • numAttempts: the number of iterations
    • interval: the interval between each attempt
    • onAttempt (optional): the function to invoke after each attempt

Installation

npm install --save tryfunc

Usage

Basic usage:

import { tryCall, tryUntil } from 'tryfunc'

function throwingFunction() {
  // ...
}

async function foo() {
  
  // try calling function
  try {
    const val = await tryCall(throwingFunc, {
      interval: 100,
      numAttempts: 10,
      onAttempt: (err, i, success) => {
        if (err) {
          console.error(err)
        }
        console.log(`attempt ${i} ${success ? 'was successful' : 'failed'}`)
      },
    })
    console.log('val', val)
  } catch (err) {
    console.error('function timed out')
  }

  // repeat until
  try {
    const val = await tryUntil(
      () => Math.random(),
      (val) => val < 0.1,
      {
        interval: 100,
        numAttempts: 10,
        onAttempt: (result, i, success) => {
          console.log('received', result)
          console.log(`attempt ${i} ${success ? 'was successful' : 'failed'}`)
        },
      },
    )
    console.log('val', val)
  } catch (err) {
    console.error('no value smaller than 0.1 produced')
  }

}
3.1.1

3 years ago

3.1.0

4 years ago

3.0.1

5 years ago

3.0.0

5 years ago

2.0.1

6 years ago

2.0.0

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago