javascript异步forEach循环
我试图在一组值(索引)上运行elasticsearch,但遇到了javaScript异步问题:javascript异步forEach循环,javascript,elasticsearch,asynchronous,foreach,Javascript,elasticsearch,Asynchronous,Foreach,我试图在一组值(索引)上运行elasticsearch,但遇到了javaScript异步问题: function(indices) { let results = []; indices.forEach(d => ESClient.search({ index: d.indexName, body: { query: { match: { first_name: 'fred'
function(indices) {
let results = [];
indices.forEach(d => ESClient.search({
index: d.indexName,
body: {
query: {
match: {
first_name: 'fred'
}
}
}
})
.then(resp => results.push(resp))
)
}
索引中应该有三个元素,我应该如何使用搜索中的所有三个响应返回结果?在您的情况下,您可以使用
map
和Promise.all
。您可以使用映射为这些索引创建一个承诺数组,即承诺。所有将等待这些承诺被解析并返回一个包含解析值的数组
function(indices) {
let results = Promise.all(indices.map(d => ESClient.search({
index: d.indexName,
body: {
query: {
match: {
first_name: 'fred'
}
}
}
})))
}
但这不是那么可读,所以我将把映射回调移到自己的函数:
function searchForIndex(d) {
return ESClient.search({
index: d.indexName,
body: {
query: {
match: {
first_name: 'fred'
}
}
}
})
}
function(indices) {
let results = Promise.all(indices.map(searchForIndex))
}
退房
有一种更好的方法,使用它,您可以在一个请求中发送所有查询,并以相同的顺序获得响应;-)@Val不错,但出于某种原因,它现在给我一个解析错误,说first_name不存在。但我确信它确实如此,因为它以前确实给了我结果,只是没有按正确的顺序推进。我想这是另一个问题。我的建议是简单地使用多搜索,而不是修补异步JS!文档中说要使用match_,但它可以与match一起使用。谢谢你的建议!!如果要向多个索引发送完全相同的查询,另一个更好的方法是简单地向该别名发送单个查询。
search(indices) {
return Promise.all(
indices.map((d) => {
return ESClient.search(yourElasticSearchPayload)
})
);
}
--------------------------------------------------------------------------
this.search(indices).then((results) => {
// do something with results
}).catch((reason) => {
// failure-reason of the first failed request
console.log(reason);
});