简体   繁体   English

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

[英]using async methods inside of array.map() in javascript

I want to go through an array of elements and then for each element check if a theme exists with the "findOne()" function and if not create a new theme and save it and if that theme exists just apply some changes and then save and i want it to only continue after the theme is saved but .我想查看一个元素数组,然后为每个元素检查一个主题是否存在“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')
})

here's my current code , i tried many ways such as async await functions or try catch blocks but never seem to solve this does anyone know where the issue could be ?这是我当前的代码,我尝试了很多方法,例如 async await 函数或 try catch 块,但似乎从未解决过这个问题有人知道问题出在哪里吗?

You probably want some sort of Promise.all implementation, so you know all of the promises you fired did return.您可能想要某种Promise.all实现,因此您知道您触发的所有承诺都返回了。

Your example code is fairly complex, so if you could simplify it I would be able to give you a more specific approach for your case.您的示例代码相当复杂,因此如果您可以简化它,我将能够为您提供更具体的方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM