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 theiterationas a parameter- (only in
tryUntil)validate: the validating function. Stops executing once the validator returnstrue. Optionsobject:numAttempts: the number of iterationsinterval: the interval between each attemptonAttempt(optional): the function to invoke after each attempt
npm install --save tryfunc
Basic usage:
import{tryCall,tryUntil}from'tryfunc'functionthrowingFunction(){// ...}asyncfunctionfoo(){// try calling functiontry{constval=awaittryCall(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 untiltry{constval=awaittryUntil(()=>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')}}