我试图通过使用ID从数据库中获取帖子,因此我遍历了一个ID数组并使用猫鼬方法'findById'来获取响应,但是该循环在完成主体之前完成了迭代。 该如何处理?
function getSortedPosts(callback){
var landingPosts = new Object;
categoryModel.find((err,categories) => {
if(err) console.log(err);
else{
categories.forEach((category,i) => {
landingPosts[category.category] = new Array;
//for each post in a category
category.posts.forEach((postid,j) => {
console.log(":")
//limiting posts per category to 3
if (j<3){
postModel.findById(postid,(err,foundpost) => {
if(err) console.log(err)
else{
landingPosts[category.category].push(foundpost);
if(i === categories.length-1){
console.log(i)
if(j === 2){
callback(landingPosts);
}
}
}
})
}
})
})
}
})
}
getSortedPosts((lp) => {.......})
我不知道如何使用Promise或异步等待...所以我正在使用回调。 现在学习它们会对我有帮助吗? (我是新手,所以我打算在目前的项目之后学习它们,这会使我感到困惑)
答案 0 :(得分:1)
我将功能划分为不同的功能,这些功能仅完成一项工作,然后将另一项功能使用这些功能来获得最终输出。像这样的东西
function findPostById(postId) {
return new Promise((resolve, reject) => {
postModel.findById(postid, (err, foundpost) => {
if (err) {
reject(err);
} else {
resolve(foundpost);
}
});
});
}
function findCategories() {
return new Promise((resolve, reject) => {
categoryModel.find((err, categories) => {
if (err) {
reject(err);
}
resolve(categories);
});
});
}
async function getSortedPosts() {
const categories = await findCategories();
const landingPosts = {};
for (const category of categories) {
for (const post of category.posts) {
const foundpost = await findById(post.postId);
landingPosts[category.category].push(foundpost);
}
}
}
我没有限制帖子数量的逻辑,但是您了解了如何构造代码。
希望这会有所帮助
答案 1 :(得分:1)
在开始这个项目之前,您绝对应该学习async await
。
async function getSortedPosts() {
var landingPosts = {};
var categories = await categoryModel.find().catch(console.log);
for(let item of categories) {
let category = item.category;
landingPosts[category] = [];
for(let id of item.posts.slice(0,2)) {
let post = await postModel.findById(id).catch(console.log);
landingPosts[category].push(post);
}
}
return landingPosts;
}
像这样调用getSortedPosts
函数-
getSortedPosts().then(landingPosts => {
// some logic
})
我没有运行代码,但希望您能解决错误。