我使用Elasticsearch JS客戶端和節點來學習ES和Javascript。我使用JavaScript構建系統SublimeText2這樣定義的運行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
輸出空數組,但問題是我怎麼能等待這些回調完成很明顯? (我不是說同步等待,而是以異步回調方式)。它可能可以用承諾來完成,但我還沒有學過承諾,現在想學習如何做這個「回調」的方式。是否有某種方法可以使JSON對象上的字符串連接不會像
[object Object]
那樣得到表示,而是使用對象字面量? (如果我打電話console.log(obj)
我得到對象字面值的字符串表示,而不是這個[object Object]
「簡寫」)。使用.toString()
是不行的。