重试node.js中https.get的逻辑

时间:2019-04-05 12:08:24

标签: node.js https retry-logic

有没有一种方法可以使用async-retry在node.js中实现https.get方法的重试。

1 个答案:

答案 0 :(得分:0)

如果您正在使用此模块https://github.com/zeit/async-retry 您的答案在README.md文件中

// 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
})

,如果您想使用更流行的解决方案/ npm模块,可以在这里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
})