When writing a Node service, you may encounter the occasional request failure when calling a third-party interface. Implement a retry mechanism to increase the success rate.

implementation

const isFunction = function(arg{

  return toString.call(arg) === '[object Function]';

};



Promise.retry = (fn, options = {}) = > {



  if(! isFunction(fn))throw new Error('fn is not a function')

  

  const { max = 3, delay = 0 } = options

  let curMax = max

  const delayExec = (a)= > delay && new Promise(resolve= > setTimeout(resolve, delay))



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

    while (curMax > 0) {

      try {

        const res = await fn()

        resolve(res)

        return

      } catch (error) {

        await delayExec()

        curMax--

        console.warn('residual number${curMax}`)

        if(! curMax) reject(error)

      }

    }

  })

}



Copy the code

test

const resolveData = (a)= > {

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

    setTimeout(

      (a)= > (Math.random() > 0.5 ? resolve('success') : reject(new Error('failure')))

      , 1000.

    )

  })

}



;(async () = > {

  try {

    const res = await Promise.retry(resolveData, { delay1000 })

    console.warn('result', res)

  } catch (error) {

    console.warn(error)

  }

}) ()



Copy the code

Welcome to talk