节点延迟重试请求

时间:2013-11-11 16:59:14

标签: javascript node.js callback delay

我正在尝试在失败之后重试请求。但是,我想延迟请求。我无法使setTimeout工作,因为我的函数测试返回的json(并且它是递归的),而setTimeout不返回回调的返回值。

function makeRequest(req, nextjson, attempts){
  // I'm using a different method here
  get({url: "http://xyz.com", json: nextjson},
    function(err, json2){
      if(err===200){
        return json2
      } else {
        // json2 might be bad, so pass through nextjson
        if(attempts < 5){
          return makeRequest(req, nextjson, attempts+1)
        } else {
          // pass back the bad json if we've exhausted tries
          return json2
        }
      }
   })
}

我想延迟递归调用的执行。此外,我对这段代码感到有点尴尬。方式太迫切了。如果你有办法清理它,我也会很感激

2 个答案:

答案 0 :(得分:2)

要从setTimout函数返回值,您必须重写函数才能使用回调:

function makeRequest(req, nextjson, attempts, callback) {
    // I'm using a different method here
    get({
        url: "http://xyz.com",
        json: nextjson
    }, function (err, json2) {
        if (err === 200 || attempts === 5) {
            callback(json2);
        } else {
            setTimeout(function () {
                makeRequest(req, nextjson, attempts + 1, callback);
            }, 1000);
        }
    });
}

并称之为:

makeRequest(requestStuff, jsonStuff, 0, function(result){
    // do stuff with result
});

我应该补充一下,你的get函数是一个异步函数(通过传入的回调很明显),因此,makeRequest函数永远不会返回任何内容,因为{{1}只有在get函数执行完毕后才会完成请求。您必须使用回调来访问异步函数返回的值。

答案 1 :(得分:1)

我建议尝试限速器来限制你的通话费用。如果您违反了限制,您将无法获得向前移动的令牌。

https://github.com/jhurliman/node-rate-limiter

示例:

var RateLimiter = require('limiter').RateLimiter;
// Allow 150 requests per hour. Also understands
// 'second', 'minute', 'day', or a number of milliseconds
var limiter = new RateLimiter(150, 'hour');

// Throttle requests
limiter.removeTokens(1, function(err, remainingRequests) {
  // err will only be set if we request more than the maximum number of
  // requests we set in the constructor

  // remainingRequests tells us how many additional requests could be sent
  // right this moment

  callMyRequestSendingFunction(...);
});