承诺内循环

时间:2016-02-02 19:38:49

标签: javascript node.js promise sails.js bluebird

var Promise = require('bluebird');

module.exports = {
  tableName: 'category',
  adapter: 'someMysqlServer',
  migrate: 'safe',
  autoCreatedAt: false,
  autoUpdatedAt: false,

  // get child categories by parent_id/category_id 
  getCategories: function(parent_id) {
    return new Promise(function(resolve, reject) {
      Category.query("SELECT * FROM category c LEFT JOIN category_description cd ON (c.category_id = cd.category_id) LEFT JOIN category_to_store c2s ON (c.category_id = c2s.category_id) WHERE c.parent_id = " + parent_id + " AND cd.language_id = '1' AND c2s.store_id = '0' AND c.status = '1' ORDER BY c.sort_order, LCASE(cd.name)", function(error, response) {
        if (error) console.log(error);
        else {
          resolve(response);
        }
      });
    });
  },

  // get left side category

  getLeftSideCategory: function() {

    var allTopCat = Category.getCategories(0);
    var cat = [];

    return new Promise(function(resolve, reject) {
      Promise.each(allTopCat, function(item, i) {

        var child = Category.getCategories(item.category_id);
        child.then(function(children, error) {
          cat[i].child = children;
          cat[i].item = item;
        });

      });
      resolve(cat);
    });
  }
}

在sails.js模型中,我需要在for循环中调用一个方法。之后,我需要收集数据并制作一个数组。然后我必须将最终的数组发送到控制器。但是我在这里得到了空白数组,之后我收到错误"Unhandled rejection TypeError: Cannot set property 'child' of undefined "。我需要在这里更改什么?

2 个答案:

答案 0 :(得分:1)

我会重构第二个函数,如下所示

getLeftSideCategory: function() {
  return Category.getCategories(0).reduce(function(finalArray, item){
    return Category.getCategories(item.category_id).then(function(children){
      finalArray.push({child: children, item: item});
      return finalArray;
    });
  }, []);
}

答案 1 :(得分:0)

getLeftSideCategory: function() {
        var allCategories=[];
  return Category.getCategories(0).reduce(function(finalArray, item){
    return Category.getCategories(item.category_id).then(function(children){

      allCategories.push({child: children, item: item});
      return allCategories;
    });
  }, []);
}

我们必须像这样编辑它现在正在使用