I have an array of items and need to create them to DB.
I need to check each insert if it success so insert to new array (results) the item + success = true as a json.
If not succeed to create - insert to the same array before (results) the item + success = false.
Here's the code:
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;
}
Now, 2 questions:
There is 'return result' after the loop is over, but i get empty array.. How should i do bulk create AND after each create, to make sure if the creation succeed?
How should i get the card in the error function? i get only 'err' as variable to the reject function.
Thanks!
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);
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With