我是一个问题的结构,无法找到相同的解决方案,我正在使用nodejs express框架,下面我放置了现有代码,我的结构像我如何调用异步函数。
exports.allProperties = function(req, res){
var categoryList = [];
Category.find({}, function(err, categories) {
categories.forEach(function(category) {
categoryList[category.id]=category;
});
getProperties(categoryList,req,res);
});
}
function getProperties(categoryList,req,res){
var propertyList = [];
var usersIds = [];
Property.find({},function(err, properties){
properties.forEach(function(property) {
propertyList.push(property);
usersIds.push(property.user_id)
});
getUsers(categoryList,propertyList, usersIds,req,res);
});
}
function getUsers(categoryList,propertyList, usersIds,req,res){
var usersList = [];
User.find({'id':{ $in: usersIds }},function(err,users){
users.forEach(function(user) {
usersList[user.id] = [];
usersList[user.id]["first_name"] = user.first_name;
usersList[user.id]["last_name"] = user.last_name;
usersList[user.id]["mail"] = user.last_name;
usersList[user.id]["contact_number"] = user.contact_number;
});
res.render('admin/allProperties.ejs', {
error : req.flash("error"),
success: req.flash("success"),
categories: categoryList,
userLists: usersList,
properties: propertyList
});
});
}
在这里我想获取所有属性,但是属性具有类别和用户,因此在属性调用中我必须调用getProperties(),而在getProperties中必须调用getUsers一样,有可能像下面这样,我想实现。 / p>
var properties = Property.find({});
var category = Category.find({});
var users = User.find({});
因此在这三行代码之后,我将所有属性,类别和用户放在一行代码中,我将管理代码并生成适当的响应并返回或呈现视图。
我如何实现这一目标?
答案 0 :(得分:2)
是的,您可以在Async-Await的帮助下实现
exports.allProperties = async function (req, res) {
let categoryList = [];
let propertyList = [];
let usersIds = [];
let categories = await Category.find({});
categories.forEach(function (category) {
categoryList[category.id] = category;
});
let properties = await Property.find({});
properties.forEach(function (property) {
propertyList.push(property);
usersIds.push(property.user_id)
});
let users = await User.find({ 'id': { $in: usersIds } });
users.forEach(function (user) {
usersList[user.id] = [];
usersList[user.id]["first_name"] = user.first_name;
usersList[user.id]["last_name"] = user.last_name;
usersList[user.id]["mail"] = user.last_name;
usersList[user.id]["contact_number"] = user.contact_number;
});
res.render('admin/allProperties.ejs', {
error: req.flash("error"),
success: req.flash("success"),
categories: categoryList,
userLists: usersList,
properties: propertyList
});
}