我在函数开头声明的数组中推送值,但最后数组为空。 我在推送后打印值并打印它们但是在exec()之外,数组是空的。 我需要获取我在organizational_with_sites变量中推送的所有值,并且需要将该数组作为响应发送。
module.exports = {getOrganizations: function (req, res) {
var userId = req.userId;
var organizations_with_sites = [];
UserPermission.find({
where: {user: userId}
}).exec(function (err, user_organizations) {
// users permitted organizations id
user_organizations.forEach(function (organization, index) {
Organization.find({
where: {id: organization.organization}
}).exec(function (err, organizations) {
// users organizations
organizations.forEach(function (organization, index) {
Site.find({
where: {organization: organization.id}
}).exec(function (err, sites) {
var organization_structure = {
id: organization.id,
name: organization.name,
address: organization.address,
sites: sites
};
organizations_with_sites.push(organization_structure);
});
});
});
});
});
return res.json({
organizations: organizations_with_sites
});}};
输出
{
"organizations": []}
答案 0 :(得分:0)
通常,很难从循环中使用异步逻辑(如从数据库中提取)的module.exports = {getOrganizations: function (req, res) {
var userId = req.userId;
var organizations_with_sites = [];
UserPermission.find({
where: {user: userId}
}).exec(function (err, user_organizations) {
// HERE track how many results you expect
var num = user_organizations.length;
// users permitted organizations id
user_organizations.forEach(function (organization, index) {
Organization.find({
where: {id: organization.organization}
}).exec(function (err, organizations) {
// users organizations
organizations.forEach(function (organization, index) {
Site.find({
where: {organization: organization.id}
}).exec(function (err, sites) {
var organization_structure = {
id: organization.id,
name: organization.name,
address: organization.address,
sites: sites
};
organizations_with_sites.push(organization_structure);
// HERE return if you have all results
if (organizations_with_sites.length >= num) {
return res.json({organizations: organizations_with_sites});
}
});
});
});
});
});
}};
循环中获取结果。你应该调查承诺来处理这个问题。
在您的情况下,您可以添加一个hacky计数器,以便在合适的时间返回。
{{1}}