Elasticsearch NodeJS : How to return result

1.1k Views Asked by At

I am trying to return a value out of a js function call as

var elasticsearch = require('elasticsearch');

var client = elasticsearch.Client({
    host: 'localhost:9200',
    log: 'trace'
});

var r="";

client.ping({
    // ping usually has a 3000ms timeout
    requestTimeout: Infinity,

    // undocumented params are appended to the query string
    hello: "elasticsearch!"
}, function (error) {
    if (error) {
        console.trace('elasticsearch cluster is down!');
    } else {
        console.log('All is well ping');
        function getmeresResult(err, result) {
            if (err) return err;
            console.log("Got res in ping "+result);
            return result;          
        }
        r=getmeres(client,getmeresResult);
        console.log("inner r is "+r);
        return r;
    }
});
console.log("outer r is "+r);

this gives me

Got res in ping 12,12,23
inner r is 12,12,23

the console.log("outer r is "+r); is never printed at all! why is that? how do i get the results 'out' of the client.ping function call?

1

There are 1 best solutions below

0
Gianni Valdambrini On BEST ANSWER

I think you are misunderstanding the way node.js works. It is asynchronous, that means that the variable r in your example is printed when the callback invoked by elasticsearch is not yet called. I imagine that you want a global r variable in order to execute some code after the elasticsearch response that use the value stored there. In that case, if you want to use the callback interface you can:

  • nest another function call from within the elasticsearch response;
  • use a library that simplify this kind of job, like async.

In the latter case you can probably use async.waterfall, and you can find an example of that with the elasticsearch js client here.