Promises.all fails to reach the catch block after the initial rejection

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?

Answer №1

The code you provided is actually creating an array filled with undefined values. This is happening because of the following syntax:

var actions = items.map((item) => { module.exports.save_single_item(item, item.id) })

To get an array of promises, you can either remove the brackets around the function body:

var actions = items.map((item) => module.exports.save_single_item(item, item.id))

Alternatively, you can explicitly return a value from the block using the "block function body" syntax:

var actions = items.map((item) => { return module.exports.save_single_item(item, item.id) })

For more information, you can visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Function_body

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue encountered while selecting the Electron app menu item

I encountered an error when clicking on a menu item: Any suggestions on how to resolve this issue? Here is the snippet of code that seems to be causing the problem: Main.js const { Menu } = require('electron') const { createNewFile } = require ...

Obtaining data from JSON arrays

My current challenge involves extracting data from the following link: and storing it in my database. However, I am encountering difficulties with manipulating the array in order to retrieve the last unix datetime. Despite multiple attempts to extract th ...

Dynamic routes in NextJS automatically append a .txt extension to the end of the URL

Issue: When using NextJS, the link <Link href="/link">link</Link> redirects to /link.txt For a simple link like this, HTML <a href="/link">link</a> can be used instead The real problem arises when using NextJS ...

Having trouble removing information from mongoDB

I'm currently using POSTMAN to delete a contact by ID, and when I do so it returns: { "n": 0, "ok": 1 } Here is the code I've written for deleting contacts: router.delete('/contact/:id', (req, res, next) => ...

The innerHTML of the p tag remains unaffected when using document.getElementsById("")

HTML {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'lessons/style.css' %}" /> <script> function openNav() { document.getElementById("mySidenav").style.width = "20%"; document.getElementById("main" ...

Vue.js application failing to display images fetched from the server

When I'm running my Vue.js app locally, the images are loading fine from the "src/assets" folder. However, when I deploy the app to Firebase, the images are not displaying and I get a 404 error. What could be causing this issue? I have tried using: ...

AngularJS: Initiate a Bootstrap modal upon webpage loading

As I work on designing a web application using AngularJS, I aim to implement the launching of a bootstrap modal upon page load through AngularJS. Here is the structure of my modal: <div class="modal hide fade" id="myModal"> <div class="moda ...

"Following successful POST login and session storage in MongoDB, the session is unable to be accessed due

When sending login data by POST with the credentials: 'include' option from client server 5500 to backend server 3000, I ensure that my session data is properly stored in MongoDB thanks to the use of 'connect-mongodb-session'. In the ba ...

Do we need to include href in the anchor tag?

Why am I unable to display the icon within the <anchor> element without using the href attribute? The icon only appears when I set the href attribute to "". Even if I manage to show the icon by adding href="", adjusting the size with width and height ...

Retrieve the data from every dropdown menu

How can I retrieve the selected values from all created selects when a button is clicked? I have attempted using both refs and v-model, but neither of them are functioning as expected. <div v-for="attribute in attributes" class="col"> {{ a ...

Combining Entities Using Immutable JavaScript

Currently utilizing React, Redux, and Immutable. I have a question about merging a plain JavaScript object into an Immutable Map object. Importing Immutable.js: import { List as iList, Map as iMap } from "immutable"; The content of action.paylo ...

Ensuring Jquery validation is triggered before submitting a form to PHP

I have been struggling with a particular issue and decided to seek help. I have a form filled with user data that I have successfully validated using js/jQuery before sending it to php for processing. Here is how I am achieving this: form.submit(functio ...

How to set the value of an `<input type="date"` in jQuery

Having trouble figuring out why this code isn't functioning properly. The input field I'm using is a simple 'input type="date"' setup like this.... <input type="date" name="Date"/> I am attempting to have the value automatically ...

How can I simultaneously add two elements to a single node or to a node that does not exist in the JSON file?

I thought this would be simple, but I'm struggling to find the answer... var crit = { 'webshopId': webshopId, 'type': 'product'} }; I need to include sku.regularPrice = { $gte : parameters.minPr ...

Tips for making a dropdown menu within an Ionic Side menu

Looking for guidance on creating a sub menu in the ionic framework? I'm new to AngularJS and ionic framework, but eager to learn. Below is the code snippet I used to create a dropdown list component: <ion-side-menu side="left"> <ion-co ...

Determining if a map array value is being duplicated with a distinct key in JavaScript

I am facing an issue with a Map that has "String" as keys and "Array" as values. My problem is figuring out how to check if an array item is present in a different "Array" value, specifically in the "Array" of a different key within the map. For example: ...

Show PDF within the browser using ajax technology

I've come across this question multiple times in various forms, but I still can't seem to find a satisfactory answer. When using the mpdf library to generate PDFs, I send some hidden field data to a PHP script via ajax. Below are snippets of the ...

"Empty array conundrum in Node.js: A query on asynchronous data

I need assistance with making multiple API calls and adding the results to an array before returning it. The issue I am facing is that the result array is empty, likely due to the async nature of the function. Any help or suggestions would be greatly appre ...

Managing messaging broadcasts for messenger bots by creating and retrieving unique identifiers

As a beginner using a starter project from glitch, I have a project set up at this link: I need help understanding how to obtain the message_broadcast_id and how to create it. This is how I usually create a normal message: function callSendAPI(messageDa ...

Tool for tracking response time on basic Ajax-requested webpage

Looking for an easy way to use ajax to load content onto a page. I want the loaded content to wait before appearing on the page, but using jQuery's .delay() function didn't work as expected. Any suggestions on how to achieve this? Appreciate any ...