0

在下面的代码中,我正在循环执行多个代理 IP 地址协议的请求。如果一个协议失败,另一个可能会成功。但是如果一个协议成功了,我不希望请求其他代理协议发生。我想终止所有请求并发送成功消息。我怎样才能做到这一点?

var request = require('request');
var ProxyAgent = require('proxy-agent');
var protocols = ['http://', 'https://', 'socks://', 'socks5://', 
'socks4://', 'pac+http://']
var proxy_list = []
function(req, res) {
  var proxy_ip = '186.94.179.162:8080'
  var web_address = `https://github.com/kyungw00k/node-ping-proxy`;
  setProxyProtocol(proxy_ip);
  for (var i = 0; i < proxy_list.length; i++) {
    getSpeed(proxy_list[i], web_address);
  }

  function setProxyProtocol(proxy_ip) {
    for (let protocol of protocols) {
      proxy_list.push(protocol + proxy_ip)
    }
  }

  function getSpeed(proxy_url, web_address) {
    try {
      var proxyUri = proxy_url;
      var agent = new ProxyAgent(proxyUri)
      var options = {
        uri: web_address,
        method: "GET",
        agent: agent,
        timeout: 10000,
        followRedirect: true,
        maxRedirects: 10,
        time: true
      }
      request(options, onResponse);
    } catch (error) {
      counter++
      if(counter<6){
        console.log('Waiting others...')
      }
      else{
        failed(error.code,counter)
      }
    }
  }

  function onResponse(error, response, body) {
    counter++;
    if (error) {
      if(counter<6){
        //other response not arrived
      }
      else{
        failed(error.code,counter)
      }
    } else {
      var speed = (response.elapsedTime);
      success(speed, counter)
    }
  }

  function success(speed, counter) {
    res.json({
      'success': true,
      'speed': speed,
      'protocol used': protocols[counter]
    })
  }

  function failed(code) {
    res.json({
      'error': true,
      'error-code': code,
      'message': "Bad request"
    })
  }
}
4

0 回答 0