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如果我的回答對你有幫助,你能接受答案嗎? –