использование asyn c методов внутри array.map () в javascript - PullRequest
0 голосов
/ 12 февраля 2020

Я хочу go через массив элементов, а затем для каждого элемента проверить, существует ли тема с помощью функции "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')
})

вот мой текущий код, я пробовал много способов, таких как asyn c функции await или пробовать блокировать блоки, но никогда кажется, решить эту проблему кто-нибудь знает, где может быть проблема?

1 Ответ

2 голосов
/ 12 февраля 2020

Возможно, вам нужна какая-то реализация Promise.all, так что вы знаете, что все выполненные обещания вернулись.

Ваш пример кода довольно сложный, поэтому, если бы вы могли упростить его, я мог бы дать вам более конкретный c подход к вашему делу.

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