2016-10-10 140 views
0

我在浏览器中使用elasticsearch.js。我想ping elasticsearch,等待请求完成,然后返回连接的结果。但现在它正在异步发生,即使连接正常,也返回undefined。我有这样的代码:Elasticsearch.js - 等待ping完成,异步调用

var connectionOK = false; 

function createElasticsearchClient(hostAddress) { 
    var client = new $.es.Client({ 
     hosts: hostAddress 
    }); 
    return client; 
} 

function checkElasticsearchConnection(client) { 
    $.when(pingElasticsearch(client)).done(function() { 
     return connectionOK; 
    }); 
} 

function pingElasticsearch(client) { 
    console.log("ELASTICSEARCH: Trying to ping es"); 
    client.ping({ 
     requestTimeout: 30000, 

     // undocumented params are appended to the query string 
     hello: "elasticsearch" 
    }, function (error) { 
     if (error) { 
      console.error('ELASTICSEARCH: Cluster is down!'); 
      connectionOK = false; 
      console.log("INSIDE: " + connectionOK); 
     } else { 
      console.log('ELASTICSEARCH: OK'); 
      connectionOK = true; 
      console.log("INSIDE: " + connectionOK); 
     } 
    }); 
} 

以及如何使用它:

var esClient = createElasticsearchClient("exampleserver.com:9200"); 
var esCanConnect = (checkElasticsearchConnection(esClient)); 

回答

0

你混合异步函数与同步功能。你可以使用这种方法,而不是去:

function createElasticsearchClient(hostAddress, callback) { 
    var client = new $.es.Client({ 
     hosts: hostAddress 
    }); 
    return callback(client); 
} 

function pingElasticsearch(client, callback) { 
    console.log("ELASTICSEARCH: Trying to ping es"); 
    client.ping({ 
     requestTimeout: 30000, 

     // undocumented params are appended to the query string 
     hello: "elasticsearch" 
    }, function (error) { 
     if (error) { 
      return callback('ELASTICSEARCH: Cluster is down!'); 
     } else { 
      return callback(null); 
     } 
    }); 
} 

然后运行

createElasticsearchClient("exampleserver.com:9200", function(esClient) { 
    pingElasticsearch(esClient, function(err) { 
    if (err) console.log(err); 
    else { 
     //Everything is ok 
     console.log('All good'); 
    } 
    }); 
}); 
+0

谢谢你,它的工作原理。 – jpiechowka

+0

嘿@jpiechowka如果我的回答对你有帮助,你能接受答案吗? –