0

Is there a way to implement retries for https.get method in node.js using async-retry.

Sterling Archer
  • 22,070
  • 18
  • 81
  • 118

1 Answers1

0

If you are using this module https://github.com/zeit/async-retry your answer is there in README.md file

// Packages
const retry = require('async-retry')
const fetch = require('node-fetch')

await retry(async bail => {
  // if anything throws, we retry
  const res = await fetch('https://google.com')

  if (403 === res.status) {
    // don't retry upon 403
    bail(new Error('Unauthorized'))
    return
  }

  const data = await res.text()
  return data.substr(0, 500)
}, {
  retries: 5
})

and if you want more popular solution/npm module you can find it here https://www.npmjs.com/package/requestretry

const request = require('requestretry');
...
// use await inside async function
const response = await request.get({
  url: 'https://api.domain.com/v1/a/b',
  json: true,
  fullResponse: true, // (default) To resolve the promise with the full response or just the body

  // The below parameters are specific to request-retry
  maxAttempts: 5,   // (default) try 5 times
  retryDelay: 5000,  // (default) wait for 5s before trying again
  retryStrategy: request.RetryStrategies.HTTPOrNetworkError // (default) retry on 5xx or network errors
})
Vinay Pandya
  • 3,020
  • 2
  • 26
  • 42