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 ?
1 Answer 1
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(...)
maphere. Map is a one-to-one functor. I am not seeing any transformation here but a lot of mutation. You should useforEach. Two, you don't need that if statement. Just do an inline if onnew_themeand eliminate the duplicate code. Last but not least, please clarify your question. I am not seeing anyasync/awaitin this code. And what do you mean bycontinue after it is saved, continue where? what is the next thing that gets executed ?Promise.allis your friend.