如何为javascript方法调用设置超时?

时间:2018-07-20 06:40:13

标签: javascript node.js

我有以下代码正在调用get_cert_info方法并尝试获取响应。

var Cert = function () {}
Cert.prototype.getCertificate = function (callback) {
  var data = [];

  Object.keys(config.endpoints).forEach(function (item) {
    get_cert_info(item, config.endpoints[item], function (res) {
      data.push(res);

      if (data.length == Object.keys(config.endpoints).length) {
        console.log(data);
        callback(null, data);
      }
    });
  });
}

这是get_cert_info方法:

function get_cert_info(endpoint, port, callback) {
  var options = {
    host: endpoint,
    port: port,
    rejectUnauthorized: false,
    agent: new https.Agent({
      maxCachedSessions: 0
    })
  };

  var req = https.get(options, function (res) {
    var certificate = res.connection.getPeerCertificate();
    var data = {};
    data['endpoint'] = endpoint;
    data['common_name'] = certificate.subject.CN;
    data['valid_from'] = certificate.valid_from;
    data['valid_to'] = certificate.valid_to;
    data['remaining'] = Math.round((new Date(certificate.valid_to) - new Date()) / (1000 * 60 * 60 * 24));
    callback(data);
  });
}

无论何时get_cert_info方法无法发送响应(由于超时或错误的端口号等),我都想处理这种情况并将消息添加到data中而不是应急。

0 个答案:

没有答案