我想遍历一个元素数组,然后对于每个元素,使用“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/