I'm new to promises and I'm saving multiple items to MongoDB database.
For a single item, I have a function that returns a promise, which rejects when the save to the database failed, or resolves if the save to the database succeeded:
exports.save_single_item = (itemBody, itemId) => {
return new Promise((resolve, reject) => {
var new_item = new Item(itemBody);
new_item.save(function (err, savedItem) {
if (err)
reject('ERROR');
else {
resolve('OK');
}
});
});
};
For multiple items, I have a function that, for each item in the submitted array containing items, calls the function above. For that, I'm using this Promise.all construction:
exports.save_multiple_items = (items) => {
var actions = items.map((item) => { module.exports.save_single_item(item, item.id) });
var results = Promise.all(actions);
results.then((savedItems) => {
console.log('ALL OK!');
}).catch((error) => {
console.log('ERROR');
});
};
The problem is, I'm never hitting the catch block on results.then.catch even though every promise call to save_single_item rejects. It goes straight into the then() block and prints out 'ALL OK'.
I'm getting UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 9): ERROR for every item in the array, even though I'm supposedly(?) catching it at the results.then.catch() block.
What am I missing here?