Answer the question
In order to leave comments, you need to log in
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+ requestsfetch
they 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'})
})
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));
})
.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);
})
$q
but 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
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 questionAsk a Question
731 491 924 answers to any question