gpt4 book ai didi

javascript - 将参数传递给 elasticsearch javascript api 搜索请求的回调函数

转载 作者:行者123 更新时间:2023-11-30 17:12:14 25 4
gpt4 key购买 nike

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

我想在回调中知道发送请求时我循环的变量 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);
});
}

最佳答案

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 的任何对象。

关于javascript - 将参数传递给 elasticsearch javascript api 搜索请求的回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26760742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com