首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Elasticsearch.js -等待ping完成,异步调用

Elasticsearch.js -等待ping完成,异步调用
EN

Stack Overflow用户
提问于 2016-10-10 13:48:54
回答 1查看 2.2K关注 0票数 0

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

代码语言:javascript
复制
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);
        }
    });
}

以及如何使用:

代码语言:javascript
复制
var esClient = createElasticsearchClient("exampleserver.com:9200");
var esCanConnect = (checkElasticsearchConnection(esClient));
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-10-10 13:55:26

异步函数和同步函数混合在一起。您可以使用这种方法来代替:

代码语言:javascript
复制
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);
        }
    });
}

然后跑

代码语言:javascript
复制
createElasticsearchClient("exampleserver.com:9200", function(esClient) {
  pingElasticsearch(esClient, function(err) {
    if (err) console.log(err);
    else {
      //Everything is ok
      console.log('All good');
    }
  });
});
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39959855

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档