[英]javascript asynchronous forEach loop
我試圖在值(索引)數組上運行elasticsearch,但遇到了javaScript異步麻煩:
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
。 您在地圖上為這些索引創建了一個Promises數組, Promise.all
等待直到這些Promises被解析,然后返回包含其解析值的數組。
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))
}
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);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.