1

在我的 node.js 应用程序中,我正在尝试构建所有弹性搜索索引的列表,并将此列表作为 JSON 发送到我的 Angular 应用程序。我正在使用 elasticsearch.js 模块:

npm install elasticsearch

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

然后,在我的 REST API 路由处理程序中,我正在 ping elasticsearch,并运行一个查询,假设返回所有索引:

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));
    }
  });
});

我假设,一旦承诺得到解决,就会有一个对象从它返回,所以我将该对象引用为“索引”,但只会得到错误“索引未定义”。

获取此类列表并将结果分配给字符串的正确方法是什么?

4

1 回答 1

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

应该

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

或更直接地

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

Promise.prototype.then将回调作为参数 - 即当承诺最终实现时要调用的函数。您的代码所说的是“调用console.log并将其返回值传递给Promise.prototype.then”。

它崩溃是因为您没有将对象引用为index,您正在访问一个index(显然)从未声明过的变量。

在我展示的版本中,被声明为传递给yourResponse的匿名箭头函数(形状为 )的第一个(也是唯一一个)参数。所以在这里填充了调用的结果,当它的承诺实现时。(...) => {...}Promise.prototype.thenyourResponse.then

于 2019-09-25T19:51:41.313 回答