我需要检查每个插入是否成功,以便将新的成功= true作为json插入到新数组中(结果).
如果创建失败,请在成功(失败)之前插入同一数组.
这是代码:
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;
}
现在,有两个问题:
>循环结束后有“返回结果”,但是我得到了空数组.
我应该如何批量创建AND,然后每次创建,以确保创建成功?
>如何获得具有错误功能的卡?我只有’err’作为拒绝函数的变量.
谢谢!
解决方法:
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);
});
}