2016-11-10 18 views
0

私は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 } 
... 

質問:

  1. 印刷resultsが空の配列を出力するのはなぜか分かりますが、これらのコールバックが完了するまでの待ち時間はどうですか? (私は同期的に待つのではなく、むしろ非同期のコールバック方式で待つことを意味する)。おそらく約束を使って行うことができますが、私はまだ約束を学んでおらず、今はこの「コールバック」方法を学びたいと思っています。

  2. JSONオブジェクトに文字列連結を作成する方法はありますか?のような表現は得られませんが、代わりにオブジェクトリテラルを使用しますか? (私がconsole.log(obj)を呼び出すと、私はオブジェクトリテラルの文字列表現を取得しますが、これは[object Object]ではありません)。 .toString()を使用すると問題ありません。

答えて

1
  1. asyncコールバックベースのアプローチを使用して非同期要求を処理するための非同期プリミティブ/ワークフローAPIを提供します。 asyncは、コレクションでの非同期操作performingの1つの方法に対してほぼ1を提供します。

    それぞれの操作にコールバックが渡されるというモデルです。操作が完了すると(成功またはエラーのいずれか)、操作はコールバックを呼び出します。 asyncでは、すべての操作が完了したときに実行されるコールバックを登録できます。

  2. 実行する必要のある非同期操作の数と完了時間を追跡することで、自分自身をロールバックすることができます。

    var numOps = content.objects.length;

    これが実行される最後のコールバックであるならば、コールバックで、あなたがチェックすることができ。

    function result_cb(err, resp) { 
        results.push({error:err, response:resp}); 
        if (results.length === numOps) { 
         // all operations have succeeded! `results` is completed 
        } 
    } 
    

    あなたは、彼らが非同期状態を維持するために同じようなことをやっているasyncソースコードを見れば。

    <オール「2」=スタート>
  3. カスタムフォーマッタ関数を作成することができます。または、標準ライブラリ関数に建て使用してオブジェクトをログに記録できます。https://stackoverflow.com/a/10729284/594589
関連する問題