使用lodash _.map处理Algolia查询结果赋值const时返回undefined问题排查
问题原因分析
- 核心错误1:
then回调没有显式返回值。你在_.map的遍历回调中写的return只会将值返回给map方法用于生成新数组,并没有把处理结果作为then回调的返回值向外传递,因此整个Promise链的最终返回值默认是undefined,被await赋值给results变量就自然得到undefined。 - 逻辑错误2:选用的遍历方法不符合需求。
_.map是遍历所有元素生成等长的新数组,不符合nbHits != 0条件的元素会返回undefined,如果你只需要第一个匹配项的hits数组,应该用_.find先筛选匹配项再取值;如果需要所有匹配项的hits集合,应该用_.filter筛选后再提取值。
修正后的代码示例
场景1:取第一个nbHits不为0的项的hits数组
const results = await algolia .multipleQueries(searchOptions, { strategy: "stopIfEnoughMatches", }) .then(({ results }) => { console.log("Step 1", results); const matchItem = _.find(results, item => _.get(item, 'nbHits') != 0) // 匹配到就返回对应的hits,没匹配到返回空数组兜底 return matchItem ? _.get(matchItem, 'hits') : [] }); console.log("Step 4", results);
场景2:取所有nbHits不为0的项的hits合并为一个数组
const results = await algolia .multipleQueries(searchOptions, { strategy: "stopIfEnoughMatches", }) .then(({ results }) => { console.log("Step 1", results); // 筛选符合条件的项后提取所有hits合并成一维数组 return _.flatMap(_.filter(results, item => _.get(item, 'nbHits') != 0), 'hits') }); console.log("Step 4", results);
额外说明
你去掉链式then回调后代码可以正常运行,是因为此时await直接拿到multipleQueries接口返回的原始响应对象,没有经过额外处理逻辑,自然不会出现then无返回值导致的undefined问题。
内容的提问来源于stack exchange,提问作者MCLarge
相关产品推荐
相关产品推荐

