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