首页 > 解决方案 > javascript异步forEach循环

问题描述

我正在尝试对一组值(索引)运行 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))
  )
}

索引中应该有三个元素,我应该如何从我的搜索中返回所有三个响应的结果?

标签: javascriptelasticsearchasynchronousforeach

解决方案


查看Promise.all

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);
});

推荐阅读