I'm completely new to promises and I'm learning how to save multiple items to a MongoDB database system.
When dealing with a single item, I have a function that utilizes promises. It returns a promise that either rejects if the database save operation fails, or resolves if the save is successful:
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');
}
});
});
};
Now, for saving multiple items, I created a function that iterates through each item in an array and calls the aforementioned function on each item. To do this, I'm using the Promise.all method like this:
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');
});
};
Unfortunately, I am facing an issue where the catch block is not being triggered even when each promise call to save_single_item ends in rejection. Instead of going to the catch block, it directly enters the then() block and displays 'ALL OK'.
Due to this, I keep receiving an UnhandledPromiseRejectionWarning for every item in the array, even though I believed I was handling it with the results.then.catch() block. What could possibly be the missing piece in my implementation?