Sequelize - 从数组

时间:2016-08-01 15:21:52

标签: javascript node.js express promise sequelize.js

我有一系列项目,需要将它们创建到DB。

如果成功,我需要检查每个插入,因此插入新数组(结果)项目+ success = true作为json。

如果没有成功创建 - 在(结果)项目+ success = false之前插入到同一个数组。

以下是代码:

create_cards: function (filter_id, is_filter, cards) {
    var result = [];
    var curr_card = null;
    for (var card in cards) {
        curr_card = this.create( {
            filter_id: filter_id,
            template: card.template,
            state: card.state,
            question_id: card.question_id || -1,
            answers: card.answers || -1,
            description: card.description || -1,
            correct_answer: card.correct_answer || -1
        }).then(function(card) {
            result.push({card: JSON.stringify(card.dataValues), success: true})
        },function(err) {
            result.push({card: card.dataValues, success: false})
        });
    }
    return results;
}

现在,2个问题:

  1. 循环结束后有'返回结果',但我得到空数组.. 我应该如何在每次创建后批量创建AND,以确保创建是否成功?

  2. 如何在错误功能中获取卡?我只将“错误”作为拒绝函数的变量。

  3. 谢谢!

1 个答案:

答案 0 :(得分:4)



create_cards: function(filter_id, is_filter, cards) {
  var result = [];

  var promises = cards.map(function(card) {
    return this.create({
        filter_id: filter_id,
        template: card.template,
        state: card.state,
        question_id: card.question_id || -1,
        answers: card.answers || -1,
        description: card.description || -1,
        correct_answer: card.correct_answer || -1
      })
      .then(function() {
        result.push({
          card: card,
          success: true
        });
      })
      .catch(function(err) {
        result.push({
          card: card,
          success: false
        });
        return Promise.resolve();
      });
  });

  return Promise.all(promises)
    .then(function() {
      return Promise.resolve(result);
    });
}