Eug*_*erg 5 node.js elasticsearch elasticsearch.js
在我的 node.js 应用程序中,我尝试构建所有 elasticsearch 索引的列表,并将该列表作为 JSON 发送到我的 Angular 应用程序。我正在使用 elasticsearch.js 模块:
npm install elasticsearch
const elasticsearch = require('elasticsearch');
const client = new elasticsearch.Client({
host: 'localhost:9200',
log: 'trace'
});
Run Code Online (Sandbox Code Playgroud)
然后,在我的 REST API 路由处理程序中,我对 elasticsearch 执行 ping 操作,并运行一个查询,该查询应该返回所有索引:
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));
}
});
});
Run Code Online (Sandbox Code Playgroud)
我假设,一旦承诺得到解决,就会从它返回一个对象,所以我将该对象引用为“索引”,但只收到错误“索引未定义”。
获取此类列表并将结果分配给字符串的正确方法是什么?
client.cat.indices({format: 'json'})
.then(console.log(index));
Run Code Online (Sandbox Code Playgroud)
应该
client.cat.indices({format: 'json'})
.then((yourResponse) => {
console.log(yourResponse);
});
Run Code Online (Sandbox Code Playgroud)
或者更直接
client.cat.indices({format: 'json'})
.then(console.log); // notice I pass the function itself, I don't call it
Run Code Online (Sandbox Code Playgroud)
Promise.prototype.then接受回调作为参数 - 即当承诺最终履行时要调用的函数。您的代码所说的是“调用console.log并将其返回值传递给Promise.prototype.then”。
它崩溃是因为您没有将对象引用为index,而是访问了一个index(显然)从未声明过的变量。
在我展示的版本中,被声明为传递给 的yourResponse匿名箭头函数(形状为 )的第一个(也是唯一)参数。So在这里填充了承诺履行时的调用结果。(...) => {...}Promise.prototype.thenyourResponse.then
| 归档时间: |
|
| 查看次数: |
3178 次 |
| 最近记录: |