tim-kos/node-retry

[Feature Request] Add Promise Support

huan opened this issue ยท 6 comments

huan commented

Suppor using Promise instead of CallBack will be very convenient.

If you agree, I'd like to make a Pull Request for it.

The p-retry library uses this library internally and allows for retrying of promises with roughly the same options this one does. Might be worth giving that a shot.

Seems to work with Promises:

export function retryable<T>(
  action: () => Promise<T>,
  options: OperationOptions
): Promise<T> {
  return new Promise((resolve, reject) => {
    const op = operation(options)
    op.attempt(async () => {
      try {
        resolve(await action())
      } catch (err) {
        if (!op.retry(err))
          reject(err)
      }
    })
  })
}

Promise instead of CallBack will be very convenient.I agree

It works out of the box ๐Ÿ˜‰

const retry = require('retry')

const isItGood = [false, false, true]
let attempt_nbr = 0

async function wait() {
  return new Promise(res => setTimeout(res, 2000))
}

async function retryer() {
  let operation = retry.operation()

  return new Promise((resolve, reject)=>{

    operation.attempt(async function(currentAttempt) {
      console.log('Attempt nbr:', attempt_nbr)
      await wait()
      console.log('...waited over')

      const err = !isItGood[attempt_nbr] ? true : null
      if (operation.retry(err)) {
        attempt_nbr++
        return
      }

      if (isItGood[attempt_nbr]) resolve('Bueno')
      else reject(operation.mainError())
    })
  })
}

async function main() {
  console.log('Start')
  await retryer()
  console.log('End')
}

main()

Maybe add an example in the README.md file with new Promise((resolve, reject) => { ... } ); ?

I have just added a modified version of @Morikko 's example to the README. Sorry for the long turn around time here. :S