javascript - Waiting for callbacks to complete in node -


i'm using elasticsearch js client , node learn es , javascript. i'm using javascript build system in sublimetext2 defined run js code:

{   "cmd": ["c:\\program files\\nodejs\\node.exe", "$file"],   "selector": "source.js" } 

wrote submit data es indexing:

"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 es6 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 + ' , 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/'); 

data source: https://github.com/dariusk/corpora/blob/master/data/humans/us_presidents.json

output:

found 66 objects. ___submitting  { website: '',   startdate: '2009-01-20',   role_type_label: 'president', ....   leadership_title: null }  results []  pushing error undefined , response  { _index: 'officials',   _type: 'president',   _id: 'avhoxercnhzrclgofuu1',   _version: 1,   result: 'created',   _shards: { total: 2, successful: 1, failed: 0 },   created: true } pushing error undefined , response  { _index: 'officials',   _type: 'president',   _id: 'avhoxerbnhzrclgofuu0',   _version: 1,   result: 'created',   _shards: { total: 2, successful: 1, failed: 0 },   created: true } ... 

questions:

  1. it's obvious why printing results outputs empty array, question how can wait callbacks complete? (i don't mean waiting synchronously, rather in async callback manner). can done using promises, have not learned promises yet , want learn how "callback" way.

  2. is there way make string concatenation on json object not representation [object object] instead use object literal? (if call console.log(obj) string representation of object literal, not [object object] "shorthand"). using .tostring() no good.

  1. async provides asynchronous primitives/workflow api handling asynchronous requests using callback based approach. async provides 1 1 way of performing async operations on collections.

    their model each operation passed callback. when operation completes (either successful or error) operation calls callback. async allows register callback execute when operations have completed.

you roll own keeping track of how many async operations need perform , when complete.

var numops = content.objects.length;

then in callback check if last callback executed.

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

if @ async source code doing similar thing maintain async states.

  1. you create custom formatter function, or log object using built in standard library functions: https://stackoverflow.com/a/10729284/594589

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -