Sequelize – 从数组批量创build

我有一系列的项目,需要创build它们到数据库。

我需要检查每个插入,如果它成功插入到新的数组(结果)项目+成功=真正的JSON。

如果没有成功创build – 插入到相同的数组之前(结果)的项目+成功= 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; } 

现在有两个问题:

  1. 循环结束后有“返回结果”,但我得到空arrays。我应该怎么做批量创build和每个创build后,以确保创build成功?

  2. 我应该如何获得卡的错误function? 我只能得到'err'作为拒绝函数的variables。

谢谢!

       

网上收集的解决方案 "Sequelize – 从数组批量创build"

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