【问题标题】:_.map not working correctly_.map 无法正常工作
【发布时间】:2013-09-17 06:33:17
【问题描述】:
var models = require('../models')
  , _ = require('underscore')
  , Restaurant = models.restaurant
  , RestaurantBranch = models.restaurant_branch;


module.exports = {
  index: function (req, res) {
    var title = 'Restaurants near you';

    RestaurantBranch.find({country: 'Ghana', region: 'Greater Accra'}, function (err, branches) {


      var results = _.map(branches, function (branch) {
        Restaurant.findById(branch._restaurantId, function (err, restaurant) {
          return {
            'restaurant': restaurant,
            'branch': branch
          };
        });
      });

      res.send(results);
    });

  }
};

我无法让 _.map 按我想要的方式工作。而不是得到一个带有对象{restaurant: restaurant, branch: branch} 的新数组。我得到了[null, null]

我尝试使用 lodash 而不是下划线,但我得到了相同的行为。

【问题讨论】:

    标签: javascript node.js underscore.js lodash


    【解决方案1】:

    问题在于您的Restaurant.findById 行。该函数似乎是异步的; _.map 是同步的。

    所以,当您返回您的数据时,为时已晚。 _.map的迭代可能已经完成了。

    对于你想要的异步东西,也许你应该考虑使用async (async.map),

    使用异步的示例:

    async.map(branches, function (branch, callback) {
      Restaurant.findById(branch._restaurantId, function (err, restaurant) {
        callback(null, { restaurant: restaurant, branch: branch });
      });
    }, function (err, results) {
        res.send(results);
    });
    

    【讨论】:

      【解决方案2】:

      我找到了解决问题的另一种方法。因为无论如何我都在使用猫鼬,所以我可以轻松地使用人口来获取餐厅数据,而不是使用下划线/lodash。

      var models = require('../models')
        , Restaurant = models.restaurant
        , RestaurantBranch = models.restaurant_branch;
      
      
      module.exports = {
        index: function (req, res) {
          var title = 'Restaurants near you';
      
          RestaurantBranch.find({country: 'Ghana', region: 'Greater Accra'})
            .populate('_restaurantId')
            .exec(function (err, branches) {
              res.send(branches);
            });
      
        }
      };
      

      【讨论】:

        猜你喜欢
        • 2021-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-01
        • 1970-01-01
        相关资源
        最近更新 更多