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));
谢谢你,它的工作原理。 – jpiechowka
嘿@jpiechowka如果我的回答对你有帮助,你能接受答案吗? –