如何重复“请求”直到成功?的NodeJS

时间:2017-09-07 23:26:47

标签: javascript node.js request timeout httpwebrequest

我在StackOverflow中检查了一些线程,但对我来说没有任何作用。 我有这个请求调用,我需要它尝试发送请求,直到它成功(但如果失败,它必须等待至少3秒):

sortingKeywords.sortVerifiedPhrase = function(phrase) {

    var URL = "an API URL"+phrase; //<== Obviously that in my program it has an actual API URL
    request(URL, function(error, response, body) {
        if(!error && response.statusCode == 200) {
            var keyword = JSON.parse(body);
            if(sortingKeywords.isKeyMeetRequirements(keyword)){ //Check if the data is up to a certain criteria
                sortingKeywords.addKeyToKeywordsCollection(keyword); //Adding to the DB
            } else {
                console.log("doesn't meet rquirement");
            }
        } else {
            console.log(phrase);
            console.log("Error: "+ error);
        }

    });
};

这是奇怪的部分,如果我从浏览器连续调用相同的短语,它几乎没有错误(它通常表明:速率限制时间已经过去)。

感谢您的帮助。 提前谢谢。

2 个答案:

答案 0 :(得分:1)

这是我为此请求撰写的工作程序。它通过函数发送请求,如果请求失败,它返回error处理程序并再次调用该函数。

如果函数成功,程序将返回一个promise并退出执行。

注意:如果您输入的网址无效,则程序会立即退出,这与request模块有关,我希望这是真实的。它会让您知道您的网址无效。因此,您必须在网址

中加入https://http://
var request = require('request');

var myReq;
//our request function
function sendTheReq(){
  myReq = request.get({
    url: 'http://www.google.com/',
    json: true
    }, (err, res, data) => {
    if (err) {
      console.log('Error:', err)
    } else if (res.statusCode !== 200) {
      console.log('Status:', res.statusCode)
    } else {
      // data is already parsed as JSON:
      //console.log(data);
    }
  })
}

sendTheReq();

//promise function
function resolveWhenDone(x) {
  return new Promise(resolve => {
    myReq.on('end', function(){
      resolve(x)
    })
    myReq.on('error', function(err){
      console.log('there was an error:  ---Trying again');
      sendTheReq();  //sending the request again
      f1();          //starting the promise again
    })
  });
}

//success handler
async function f1() {
  var x = await resolveWhenDone(100);
  if(x == 100){
      console.log("request has been completed");
      //handle other stuff
  }
}

f1();

答案 1 :(得分:0)

出错时运行此代码

setTimeout(function(){}, 3000);

请参阅此https://www.w3schools.com/jsref/met_win_settimeout.asp

你也可以制作这样的代码

var func1 = function(){}; setTimeout(func1, 3000);