V
V
Vitaly2017-08-02 15:27:49
JavaScript
Vitaly, 2017-08-02 15:27:49

How to correctly send HTTP requests in a loop?

All the best!
Faced the problem of sending more than 200 requests to resources that are not always available.
Now I'll try the details:
I have a pool of 200+ ip addresses 192.168.1.1 - 192.168.1.254, among which, approximately only 3 ip are valid, but I don't know which ones, and each time it can be different ip.
That is, 1-3 machines with unknown IPs (only the pool is known) on which the http server is launched and listens to requests.
And this is when I run a loop with 200+ requestsfetchthey reach their destination like when, 50 to 50. In this case, I don’t need a response from the servers, I only need to send a request 100%, but due to the fact that most of the addresses are not valid, there is no http server or other device at all, I have errors, through which requests may not reach the desired addresses. Here is the code:

servers.forEach(server=>{
         fetch(`http://${server}:3347/off`, {method: 'POST'})
  })

or:
function fetchWrapper(server) {
  return fetch(`http://${server}:3347/off`, {method: 'POST'}).then(response => {
    return response.json().then(json => {
      return response.ok ? json : Promise.reject(json);
    });
  });
}


servers.forEach(server=>{
         fetchWrapper(server).then(console.log.bind(console));
  })

Sometimes everything goes well, and sometimes the request does not pass, and sometimes you have to wait too long (then even in other tabs nothing is loaded)
I have another part written in Angular 1, but there I already need an answer:
.factory('extRequest',($http)=>{
    return {
      getList : (ip)=> {
        return $http.get(`http://${ip}:3347/identify`,{timeout: 2000}).
          then(answ=>{
          return answ['data']
        })
        
      } 
             })


angular.forEach(ips,(ip)=> {
  extRequest.getList(ip).then(term =>{
      $scope.list.push(term);
  })

In Angular, you probably need to use queues, $qbut I somehow didn’t find or didn’t understand any suitable examples.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Azamat Kasymbekov, 2017-08-10
@artmadiar

I would recommend this design:

// выполнить все запросы разом
Promise.all(servers.map(server=>fetchWrapper(server)))
// дождаться выполнения всех
.then((results) => {
...
})
// минус в том, что если хоть один руганется, то слетит всё. Но как я понял, 404 или 500 это не ошибка
.catch(err => console.error(err))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question