【发布时间】:2016-11-11 00:33:51
【问题描述】:
我正在使用 Elasticsearch JS 客户端和节点来学习 ES 和 Javascript。我正在使用这样定义的 SublimeText2 中的 Javascript 构建系统来运行 JS 代码:
{
"cmd": ["C:\\Program Files\\nodejs\\node.exe", "$file"],
"selector": "source.js"
}
写这个是为了将数据提交给 ES 进行索引:
"use strict";
const es = require('elasticsearch');
const path = require('path');
const fs = require('fs');
function es_connect(url, loglevel) {
if (typeof loglevel === 'undefined') { // somehow default function params feature from ES6 is not available in installable node/js
loglevel == 'error';
}
return new es.Client({host: url, log:loglevel});
}
function get_content(fname) {
const raw = fs.readFileSync(path.join('data', fname));
const content = JSON.parse(raw);
console.log('Found ' + content.objects.length + ' objects.');
return content;
}
function index_json_list(fname, index, doc_type, url) {
var content = get_content(fname);
var client = es_connect(url);
var results = [];
function result_cb(err, resp) {
console.log('Pushing error ' + err + ' and response ');
console.log(resp);
results.push({error:err, response:resp});
};
content.objects.forEach(function(x) {
console.log('___Submitting ');
console.log(x);
client.index({
index: index,
type: doc_type,
body: x
},
result_cb);
});
results.forEach(function(x){
console.log('indexing result: ' + x);
})
console.log('results');
console.log(results);
}
index_json_list('us_presidents.json', 'officials', 'president', 'http://localhost:9200/');
数据来源:https://github.com/dariusk/corpora/blob/master/data/humans/us_presidents.json
输出:
Found 66 objects.
___Submitting
{ website: '',
startdate: '2009-01-20',
role_type_label: 'President',
....
leadership_title: null }
results
[]
Pushing error undefined and response
{ _index: 'officials',
_type: 'president',
_id: 'AVhOXERCNHzrCLGOfUu1',
_version: 1,
result: 'created',
_shards: { total: 2, successful: 1, failed: 0 },
created: true }
Pushing error undefined and response
{ _index: 'officials',
_type: 'president',
_id: 'AVhOXERBNHzrCLGOfUu0',
_version: 1,
result: 'created',
_shards: { total: 2, successful: 1, failed: 0 },
created: true }
...
问题:
打印
results输出空数组的原因很明显,但问题是如何等待这些回调完成? (我的意思不是同步等待,而是异步回调的方式)。可能可以使用 Promise 完成,但我还没有学习 Promise,现在想学习如何执行这种“回调”方式。有什么方法可以在 JSON 对象上进行字符串连接,而不是像
[object Object]这样的表示,而是使用对象文字? (如果我打电话给console.log(obj),我会得到对象文字的字符串表示,而不是[object Object]“速记”)。使用.toString()不好。
【问题讨论】:
标签: javascript json node.js callback