简体   繁体   中英

How to loop a request in node.js

so I recently started learning coding, and I wanted to know how I can multiply/loop this request instead of it being sent only once.

request({
    url: URL,
    method: 'GET',
    json: true
}, function (error, response, body){
    if(error){
        console.log("Error!")
    } else if(!error && response.statusCode == 200){
        console.log(chalk.green('Entered successfuly!'))
    }
})

The request can be sent many times over time using a setTimeout loop:

function sendRequest() {

  setTimeout(function() {

    $.ajax({
        url: 'http://localhost/example',
        method: 'GET',
        json: true
    }, function (error, response, body){
        if(error){
            console.log("Error!")
        } else if(!error && response.statusCode == 200){
            console.log(chalk.green('Entered successfuly!'))
        }
    });

    sendRequest();

  }, 1000);

}

sendRequest();

Or as an interval function:

function sendRequest() {

  $.ajax({
      url: 'http://localhost/example',
      method: 'GET',
      json: true
  }, function (error, response, body){
      if(error){
         console.log("Error!")
      } else if(!error && response.statusCode == 200){
          console.log(chalk.green('Entered successfuly!'))
      }
  });

}

let interval = setInterval(sendRequest, 1000);

If you'd like to send the request a fixed number of times, the first function can be modified like that:

function sendRequest(i) {

  if (i > 0) {

    setTimeout(function() {

      $.ajax({
          url: 'http://localhost/example',
          method: 'GET',
          json: true
      }, function (error, response, body){
          if(error){
              console.log("Error!")
          } else if(!error && response.statusCode == 200){
              console.log(chalk.green('Entered successfuly!'))
          }
      });

      sendRequest(i - 1);

    }, 1000);

  }

}

sendRequest(3);

A loop will call the function as fast as your computer can process it. Instead put it into a timeout that calls itself so you can regulate the requests.

function makeRequest(){
 request({
    url: URL,
    method: 'GET',
    json: true
 }, function (error, response, body){
    if(error){
        console.log("Error!")
    } else if(!error && response.statusCode == 200){
        console.log(chalk.green('Entered successfuly!'))
    }
 })
 setTimeout(makeRequest,1000)
}
makeRequest()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM