【问题标题】:How to handle async when making mongoose query in each array element in express?在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)

【问题讨论】:

    标签: node.js express mongoose async-await


    【解决方案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);
        }
    });
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-04
      • 2016-05-14
      • 2021-03-06
      • 2021-03-04
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      相关资源
      最近更新 更多