0

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 .

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 ?

6
  • 2
    first of all. Don't use map here. Map is a one-to-one functor. I am not seeing any transformation here but a lot of mutation. You should use forEach. Two, you don't need that if statement. Just do an inline if on new_theme and eliminate the duplicate code. Last but not least, please clarify your question. I am not seeing any async/await in this code. And what do you mean by continue after it is saved, continue where? what is the next thing that gets executed ? Commented Feb 12, 2020 at 15:25
  • IF you decide to go that route there are addtional steps you would need to go. For example, your map function would need to return a Promise and ther resulting value would be a Promise[]. You would then have to do a await Promise.wait(x) essentially. I have had to do a similar concept once because I had a list of Async functions which needed to be resolved before the app continued. Yours is similar issue building out the async list through map instead of me creating 2-3 specific async functios. Commented Feb 12, 2020 at 15:31
  • 1
    This function is 36 lines long and indented 6 levels deep. It's a good indication for dividing that logic into a few smaller, named functions. Also: if you want to wait until all of several parallel async operations have completed, then Promise.all is your friend. Commented Feb 12, 2020 at 15:31
  • I think you still need to await the result from promise all, as that just resolves when all items in the promise list resolve. Commented Feb 12, 2020 at 15:33
  • @sinanspd that code is executed for each element of the array so what i mean by continue is for the current element save and after that continue to do the same thing for the next element Commented Feb 12, 2020 at 15:40

1 Answer 1

2

You probably want some sort of Promise.all implementation, so you know all of the promises you fired did return.

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(...)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.