3

In my node.js app, I'm trying to build a list of all elasticsearch indices and send this list as JSON to my Angular app. I'm using elasticsearch.js module:

npm install elasticsearch

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

Then, in my REST API route handler, I'm pinging elasticsearch, and running a query, which suppose to return all indices:

indexRoutes.route('/').get(function (req, res) {
  client.ping({
    requestTimeout: 30000,
  }, function (error) {
    if (error) {
      console.error('elasticsearch cluster is down!');
    } else {
      console.log('All is well');
      client.cat.indices({format: 'json'})
          .then(console.log(index));
    }
  });
});

I assume, that once the promise is resolved, there would be an object returned from it, so I'm referencing that object as "index", but only getting the error "index is not defined".

What is the proper way to obtain such listing and assign the result to a String?

Eugene Goldberg
  • 14,286
  • 20
  • 94
  • 167

1 Answers1

5
client.cat.indices({format: 'json'})
.then(console.log(index));

should be

client.cat.indices({format: 'json'})
.then((yourResponse) => {
  console.log(yourResponse);
});

or more directly

client.cat.indices({format: 'json'})
.then(console.log); // notice I pass the function itself, I don't call it

Promise.prototype.then takes a callback as an argument - i.e. a function to be called when the promise eventually fulfills. What your code says is "call console.log and pass its returned value to Promise.prototype.then".

It crashes because you're not referencing an object as index, you're accessing an index variable that was (apparently) never declared.

In the version I show, yourResponse is declared as the first (and only) parameter of an anonymous arrow function (shaped as (...) => {...}) that is passed to Promise.prototype.then. So yourResponse is here populated with the result of the call by .then when its promise fulfills.

Stock Overflaw
  • 3,203
  • 1
  • 13
  • 14