【问题标题】:Pass parameters to a callback function of a elasticsearch javascript api search request将参数传递给elasticsearch javascript api搜索请求的回调函数
【发布时间】:2016-02-23 16:50:17
【问题描述】:

我有一个函数,它要求对用户给出的每个单词进行聚合,然后绘制一个图表。

我想在回调中知道发送请求时我的循环的变量 i 的值是多少。

如何在 elasticsearch API 固定的预定义参数中传递变量 i?

for(var i = 0; i < 15; i++)
{
    client.search({
        index: 'twitter',
        type: "status",
        size : 10,
        body: 
        {
            query: {
                "bool": {
                    "must": [
                        {"query_string": {
                            "fields" : ["text"],
                            "default_operator" : "AND",
                            "query" : $scope.motsCompares[i]
                        }},
                        {"range": {
                            "created_at": {
                                "gte": moment().subtract(duration, key).format("YYYY-MM-DD")
                            }
                        }}
                    ]
                }
            },
            aggs : {
                "frequence_mots" : {
                    "date_histogram" : {
                        "field" : "created_at",
                        "interval" : "day",
                        "format" : "dd/MM/yyyy",
                        "min_doc_count" : 0
                    }
                }
            }
        }
    }).then(function traiterResultat(body) {

        // I would like to use i from the loop here to get the right word in my array ($scope.motsCompares[i])

    }, function (error) {
            console.trace(error.message);
    });
}

【问题讨论】:

    标签: javascript callback elasticsearch promise


    【解决方案1】:

    fn.bind() 出现之前,这种事情需要关闭或其他可怕的方法,我什至不会提及它们。

    从 ECMAScript 5 开始,您可以利用 fn.bind() 的“currying”特性立即传递 i 并稍后传递 body,当 Promise 链破坏其成功路径时。

    for(var i = 0; i < 15; i++) {
        (function(i) {
            client.search({
                // ...
            }).then(function (i, body) {
                //.then()'s callback is an intermediate function returned by .bind().
                // `i` here is the loop's `i` that was bound-in by .bind().
                //`body` is passed to the intermediate function later, when the promise chain rips down its success path.
            }.bind(null, i), function (error) {
                console.trace(error.message);
            });
        })(i);
    }
    

    您可以在回调中将.bind(null, i) 中的null 更改为您想成为this 的任何对象。

    【讨论】:

      【解决方案2】:

      使用另一个函数来创建你的回调:

      for(var i = 0; i < 15; i++)
      {
        client.search({
                        index: 'twitter',
                        type: "status",
                        size : 10,
                        body:
                        {
                          query: {
                            "bool": {
                              "must": [
                                {"query_string": {
                                  "fields" : ["text"],
                                  "default_operator" : "AND",
                                  "query" : $scope.motsCompares[i]
                                }},
                                {"range": {
                                  "created_at": {
                                    "gte": moment().subtract(duration, key).format("YYYY-MM-DD")
                                  }
                                }}
                              ]
                            }
                          },
                          aggs : {
                            "frequence_mots" : {
                              "date_histogram" : {
                                "field" : "created_at",
                                "interval" : "day",
                                "format" : "dd/MM/yyyy",
                                "min_doc_count" : 0
                              }
                            }
                          }
                        }
                      }).then(createCallback(i), function (error) {
                                console.trace(error.message);
                              });
      }
      
      function createCallback(i){
        return function traiterResultat(body) {
      
          // use i from the loop here to get the right word in my array ($scope.motsCompares[i])
      
        }
      }
      

      【讨论】:

      • 有效!谢谢你。所以回调函数可以访问其直接父级的上下文,这就是想法?
      • @Ganoninc 如果他解决了你的问题 - 考虑接受这个答案。
      • 是的,请接受答案:)。要回答您的第二个问题 - 每个新功能都会创建一个新范围。来自外部范围的任何变量都可以在内部范围内“封闭”。 developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures
      猜你喜欢
      • 2016-09-19
      • 2011-03-28
      • 2011-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多