更改在 exec 函数 sailjs 外部声明的变量

Changing the variable declared outside the exec function sailjs

我将值推送到函数开头声明的数组中,但最后数组为空。 我在推送后打印值,它打印它们但在 exec() 之外,数组是空的。 我需要获取我在 organizations_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": []}

一般来说,很难从 forEach 循环中获得结果,因为循环中使用了异步逻辑(比如从数据库中获取数据)。您应该调查一般处理此问题的承诺。

在您的情况下,您可以在适当的时候向 return 添加一个骇人听闻的计数器。

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});
            }

          });
        });

      });
    });

  });
}};