javascript - 在 javascript 中使用 array.map() 内部的异步方法

标签 javascript node.js async-await

我想遍历一个元素数组,然后对于每个元素,使用“findOne()”函数检查主题是否存在,如果不存在,则创建一个新主题并保存它,如果该主题存在,则只需应用一些更改,然后然后保存,我希望它仅在保存主题后继续,但是。

internalRoutes.post('/add_questions', (req, res) => {
    let elements = req.body
    var count = 0;
    elements.map((element) => {
        let q = new Question({ category: element.category, body: element.body, level: element.level })
        q.save().then(question => {

            Theme.findOne({ name: element.theme }).then(theme => {
                if (!theme) {
                    let new_theme = new Theme({ name: element.theme, level: element.level, questions: [], first_question: null })
                    new_theme.questions.push(question);
                    new_theme.first_question = question._id;
                    new_theme.save().then(t => {
                        console.log('new theeeeemmmmmmeeeeee')
                    })
                }
                else {
                    theme.questions.push(question);
                    theme.save().then(t => {
                        console.log('yeeeerrrrrrrrrrrrrecognized');
                    })
                }
            })
                .catch(err => {
                    res.status(400).json("couldn't locate theme")
                })
        }).catch(err => {
            res.status(400).json("couldn't save question")
        })
        count++;

    })
    if (count === elements.length) {
        res.status(200).json({ message: "questions added successfully" })
    }
    else res.status(500).json('error')
})

这是我当前的代码,我尝试了很多方法,例如异步等待函数或 try catch block ,但似乎从未解决这个问题,有人知道问题可能出在哪里吗?

最佳答案

您可能需要某种 Promise.all 实现,这样您就知道您发出的所有 promise 确实返回了。

您的示例代码相当复杂,因此如果您可以简化它,我将能够为您的案例提供更具体的方法。

const promisedElements = Promise.all(elements.map(async () => { ... })).then(...)

关于javascript - 在 javascript 中使用 array.map() 内部的异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60191513/

相关文章:

c# - 如何在 .NET 4.0 中使用 Microsoft.Bcl.Async 支持 TransactionScope 中的异步方法?

c# - 顶级工作方法中的异步模式

javascript - ajax load() 后不会重新绘制包含图表的图像

node.js - 带有 Websocket 的 Nodejs REST API

javascript - 为什么我无法在 bootstrap 表中填充 json 数据

PHP 和 C++ 发送/接收事件

javascript - 使用 mongorestore 将许多文档插入临时集合

c# - 线程有等待语句吗?

javascript - 如何链接一系列返回 promise 并需要不同参数的函数?

javascript - 我的第一个脚本成功了! - 除了 IE 和 Safari - 请帮忙