0

I'm trying to program a nodejs server that read all documents in an elsaticsearch index, and return a javascript array that contains the title field for each document.

This is my JavaScript code:

let elasticsearch = require('elasticsearch')

const esClient = new elasticsearch.Client({
    host: '127.0.0.1:9200',
    log: 'error'
});

let titles = new Array()

esClient.search({
    index: 'myindex',
    type: 'mytype',
    body: {
        size: 5,
        from: 0,
        query: {
            match_all: {}
        }
    }
  }).then(function (resp) {
      var hits = resp.hits.hits;
      hits.forEach((hit, index) => titles.push(hit._source.title));

  }, function (err) {
      console.trace('err.message');
});

console.log(titles)

But the output of titles still empty [] after execution

Do you have an idea about how should I code it? if what I want to do is possible with javascript.

Thank you in advance

M. Ben
  • 1
  • 1
  • Yes. That's because `.search()` is _asynchronous_. You populate `titles` in the `.then` function (which is good), so it's correct in there (try to log it). Asynchronism means that the lines of code are not executed one by one, in order (like PHP), but only when the data is ready. – Jeremy Thille May 23 '18 at 14:15
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Jeremy Thille May 23 '18 at 14:15

0 Answers0