简体   繁体   English

等待节点中的回调完成

[英]Waiting for callbacks to complete in node

I'm using Elasticsearch JS client and node to learn ES and Javascript. 我正在使用Elasticsearch JS客户端和节点来学习ES和Javascript。 I'm using Javascript build system in SublimeText2 defined like this to run the JS code: 我正在SublimeText2中使用Javascript构建系统进行定义,以运行JS代码:

{
  "cmd": ["C:\\Program Files\\nodejs\\node.exe", "$file"],
  "selector": "source.js"
}

Wrote this to submit data to ES for indexing: 编写此文件以将数据提交给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/');

Data source: https://github.com/dariusk/corpora/blob/master/data/humans/us_presidents.json 数据来源: 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 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 }
...

Questions: 问题:

  1. It's obvious why printing results outputs empty array, but the question is how can I wait for those callbacks to complete? 很明显为什么打印results输出空数组,但是问题是我如何等待这些回调完成? (I don't mean waiting synchronously, but rather in async callback manner). (我不是说同步等待,而是以异步回调的方式)。 It can probably be done using promises, but I have not learned promises yet and for now want to learn how to do this "callback" way. 可以使用promise来完成,但是我还没有学习promise,并且现在想学习如何执行这种“回调”方式。

  2. Is there some way to make string concatenation on JSON object not to get the representation like [object Object] but instead use object literal? 有什么方法可以在JSON对象上进行字符串连接,而不是像[object Object]那样获得表示,而是使用对象文字? (if I call console.log(obj) I get string representation of object literal, not this [object Object] "shorthand"). (如果我调用console.log(obj)则会得到对象文字的字符串表示形式,而不是此[object Object] “简写形式”)。 Using .toString() is no good. 使用.toString()不好。

  1. async provides asynchronous primitives/workflow api for handling asynchronous requests using callback based approach. async提供异步原语/工作流api,用于使用基于回调的方法处理异步请求。 async provides almost 1 for 1 way of performing async operations on collections. 异步提供了一种在集合上执行异步操作的几乎1比1的方式。

    Their model is that each operation is passed a callback. 他们的模型是每个操作都传递一个回调。 When the operation completes (either successful or error) that operation calls the callback. 操作完成(成功或错误)后,该操作将调用回调。 async allows you to register a callback to execute for when all operations have completed. 异步允许您注册所有操作完成后要执行的回调。

You could roll your own by keeping track of how many async operations you need to perform and when they are complete. 您可以通过跟踪需要执行多少异步操作以及它们何时完成来滚动自己的记录。

var numOps = content.objects.length;

then in the callback you could check if this is the last callback to be executed. 然后在回调中,您可以检查这是否是要执行的最后一个回调。

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

If you look at the async source code they are doing a similar thing to maintain the async states. 如果您查看async源代码,它们会做类似的事情来维护异步状态。

  1. You could create a custom formatter function, or you could log the object using built in standard library functions: https://stackoverflow.com/a/10729284/594589 您可以创建自定义格式化程序功能,也可以使用内置的标准库功能记录对象: https : //stackoverflow.com/a/10729284/594589

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM