在我的 node.js 应用程序中,我正在尝试构建所有 Elasticsearch 索引的列表,并将此列表作为 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));
}
});
});
我假设,一旦 promise 得到解决,就会有一个对象从它返回,所以我将该对象引用为“索引”,但只会得到错误“索引未定义”。
获取此类列表并将结果分配给字符串的正确方法是什么?
最佳答案
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
将回调作为参数 - 即当 promise 最终实现时要调用的函数。您的代码所说的是“调用 console.log
并将其返回值传递给 Promise.prototype.then
”。它崩溃是因为您没有将对象引用为
index
,您正在访问 index
(显然)从未声明过的变量。在我展示的版本中,
yourResponse
被声明为传递给 (...) => {...}
的匿名箭头函数(形状为 Promise.prototype.then
)的第一个(也是唯一的)参数.所以yourResponse
此处填充了 .then
的调用结果当它的 promise 实现时。
关于node.js - 如何正确列出 node.js 中的所有 Elasticsearch 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58102867/