私はElasticsearch JSクライアントとノードを使ってESとJavascriptを学習しています。私はJavascriptがJSコードを実行するために、次のように定義されたSublimeText2でシステムを構築し使用しています:ノードでコールバックが完了するのを待っています
{
"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オブジェクトに文字列連結を作成する方法はありますか?のような表現は得られませんが、代わりにオブジェクトリテラルを使用しますか? (私が
console.log(obj)
を呼び出すと、私はオブジェクトリテラルの文字列表現を取得しますが、これは[object Object]
ではありません)。.toString()
を使用すると問題ありません。