【问题标题】:How to repeat a "request" until success? NODEJS如何重复“请求”直到成功?节点
【发布时间】:2017-09-07 23:26:47
【问题描述】:

我在 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);
        }

    });
};

这是奇怪的部分,如果我从浏览器中连续调用相同的短语,它几乎可以正常工作(通常会显示:速率限制时间已超过)。

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

【问题讨论】:

    标签: javascript node.js request timeout httpwebrequest


    【解决方案1】:

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

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

    注意:如果您输入了无效的 url,程序会立即退出,这与 request 模块有关,老实说。它让您知道您的网址无效。所以你必须在url中包含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();
    

    【讨论】:

      【解决方案2】:

      出错时运行此代码

      setTimeout(function(){}, 3000);

      看到这个https://www.w3schools.com/jsref/met_win_settimeout.asp

      你也可以这样写代码

      var func1 = 函数(){}; setTimeout(func1, 3000);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-28
        • 1970-01-01
        • 1970-01-01
        • 2015-07-18
        • 2016-02-16
        相关资源
        最近更新 更多