代码之家  ›  专栏  ›  技术社区  ›  sale108

如何重复“请求”直到成功?节点JS

  •  2
  • sale108  · 技术社区  · 7 年前

    我有这个请求调用,我需要它尝试发送请求,直到成功(但如果失败,它必须等待至少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 回复  |  直到 7 年前
        1
  •  2
  •   Ahmed Can Unbay    7 年前

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

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

    注意:如果您输入的url无效,程序会立即退出,这与 request 老实说,我喜欢这个模块。它让你知道你有一个无效的url。所以你必须包括 https:// http:// 在url中

    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
  •  0
  •   muasif80    7 年前

    出错时运行此代码

    setTimeout(function(){}, 3000);

    https://www.w3schools.com/jsref/met_win_settimeout.asp

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