在express中的每个数组元素中进行猫鼬查询时如何处理异步?
Posted
技术标签:
【中文标题】在express中的每个数组元素中进行猫鼬查询时如何处理异步?【英文标题】:How to handle async when making mongoose query in each array element in express? 【发布时间】:2020-09-12 17:06:16 【问题描述】:在以下发布方法中,由于月光异步,我遇到了一些问题。先执行res.send(suggestions)
,然后执行Expense.findOne.exec
app.post('/suggestions', async function(req, res)
const suggestions = await req.body.map((description) =>
Expense.findOne( description: new RegExp(description, 'i') ).exec((err, result) =>
if (result)
console.log(result.newDescription);
return
description,
newDescription: result.newDescription,
category: result.category,
subcategory: result.subcategory
;
);
);
res.send(suggestions);
);
结果是一个空值数组。如何对每个项目执行查询,然后执行res.send(suggestion)
?
【问题讨论】:
【参考方案1】:使用以下代码找到解决方案:
app.post('/suggestions', async function(req, res)
try
if (req.body.length > 0)
const suggestions = req.body.map((description) =>
Expense.findOne( description: new RegExp(description, 'i') )
);
const results = await Promise.all(suggestions);
return res.send(results);
catch (e)
console.log('error', e);
);
【讨论】:
以上是关于在express中的每个数组元素中进行猫鼬查询时如何处理异步?的主要内容,如果未能解决你的问题,请参考以下文章