What could be causing this Promise to bypass the forEach loop?

I'm encountering an issue with this block of code. While attempting to return a Promise, I've noticed that during debugging, it seems to "skip" the forEach loop and rejects the function instead. Can you help me identify what might be causing this behavior?

removeOldBookings(rooms: Room[]) {
  return new Promise((resolve, reject) => {
    const today = new Date();
    const roomsHolder = [];
    rooms.forEach(roomElement => {
      const bookingFiltered = roomElement[1].filterRoom.filter(finder => finder.provider.toUpperCase() === 'SELF');
      if (new Date(bookingFiltered.dateEnd) > today) {
        const obj = {...roomElement[1], hostBookings: [...bookingFiltered]};
        roomsHolder.push(obj);
      }
    });
    if (roomsHolder.length) {
      resolve(roomsHolder);
    } else {
      reject('error');
    }
  });
}

Answer №1

According to charlietfl's explanation, when using filter in

roomElement[1].filterRoom.filter(...)
, an array is returned, making bookingFiltered an array as well. However, since bookingFiltered.dateEnd is undefined, it results in an invalid date which then converts to NaN when used with > (greater than) comparison. Given that NaN will never be greater than anything, the code within the if block will not be executed, resulting in roomsHolder always being empty.

If you are aiming to retrieve the first item from an array that meets a specific condition, consider using find instead:

const bookingFiltered = roomElement[1].filterRoom.find(finder => finder.provider.toUpperCase() === 'SELF')

In addition, following Daniel A. White's advice, it is unnecessary to return a promise at this point. Rather, you can simply return roomsHolder and throw an error if needed:

removeOldBookings(rooms: Room[]) {
  const today = new Date();
  const roomsHolder = [];
  rooms.forEach(roomElement => {
    const bookingFiltered = roomElement[1].filterRoom.find(finder => finder.provider.toUpperCase() === 'SELF');
    if (new Date(bookingFiltered.dateEnd) > today) {
      const obj = {...roomElement[1], hostBookings: [...bookingFiltered]};
      roomsHolder.push(obj);
    }
  });
  if (roomsHolder.length) {
    return roomsHolder;
  } else {
    throw 'error';
  }
}

If returning a promise is necessary for any reason, you can also declare the method as async function or utilize Promise.resolve(roomsHolder) for success and Promise.reject('error') for failure, rather than encapsulating everything within the promise constructor.

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

Why is the text returned by the Angular Response body missing the JSON brackets? Strange, isn't it

As a newcomer to Angular 2, I should mention that some information is internal and will be replaced with placeholders when needed. My current task involves making a simple post request and retrieving the contents of the request body. Below is my existing ...

What is the best way to gather Data URI content through dropzone.js?

I am currently utilizing Dropzone for its thumbnail generation feature and user interface. However, I am only interested in using the thumbnail generation ability and UI and would prefer to collect all the data URIs myself and send them to the server via a ...

Using Laravel 8 to create connected dropdown menus with the power of Ajax

Struggling with setting up a dependent dropdown menu in Laravel 8 using Ajax. The first dropdown works fine, but the next two don't display any options. Being new to Laravel, I'm having trouble pinpointing the problem areas. Seeking assistance to ...

Transferring files from the android_asset directory to the SD Card

I am trying to play video files that are packaged within a Cordova application. My goal is to transfer these files from the android_asset folder to the SD card using the File API in JavaScript. However, I am encountering difficulties in accessing this fol ...

Could someone clarify why EventEmitter leads to issues with global variables?

I recently encountered an error that took me some time to troubleshoot. Initially, I decided to create a subclass of EventEmitter In the file Client.js var bindToProcess = function(func) { if (func && process.domain) { return process.domai ...

Is it possible to host multiple React applications on a single port? Currently experiencing issues with running both an Admin panel and the Front side in production mode on the same Node.js API server

Is it possible to host multiple React applications on the same port? I am experiencing issues with running both an Admin panel and a Front side React app in production mode on the same Node.js API server. ...

Vuetify: The checkbox displays the opposite status of whether it is checked or unchecked

Can you help me simplify this problem: In my Vue.js template using Vuetify components, there is a checkbox present: <v-checkbox v-model="selected" label="John" value="John" id ="john" @click.native="checkit"> </v-checkbox> ...

Is it possible for external sources to change the values stored in local storage of an

Currently, I am in the process of creating a mobile app using jQuery Mobile and PhoneGap. One of the functionalities I've implemented is user login, where I store the logged-in user's ID in local storage to track their activities. While my appli ...

Tips for Sending Information to the Current Page Using JQuery

I am attempting to send the form data back to the same location as the form itself. The code needs to: Trigger the click action for #submit Retrieve data from #email, #selection1, and #selection2 Hide the form #form Show the data in #email, #selection1, ...

Error encountered during Typescript compilation: Type 'void' cannot be assigned to type 'Item[]'

Below are my typescript functions. When I edit in vscode, the second function does not show any error message. However, upon compilation, an error is displayed for the second function: error TS2322: Type 'Promise<void>' is not assignable t ...

Working with ReactJS, Material-UI, and Javascript: Facing challenges in applying rounded borders to TableRow components

I've been trying to achieve rounded borders on a TableRow element, but adding the style "borderRadius: 5" doesn't seem to have any effect. When I try wrapping the TableRow in a Box element with borderRadius, it does make the borders rounded but m ...

Could you provide me with a demonstration of cross-domain functionality?

Similar Inquiry: Methods to bypass the same-origin policy Let's consider two domains for this example - "" and "". The first domain "" is generating data in JSON format as shown below: { "str_info": [ { "str_name": "Mark ...

Guide to playing a gif solely through an onclick event using JavaScript

Below you will find a code that is used to load a gif animation from an array of characters, and then display it within a board class using the image src. I am looking to make the gif animation play only when the displayed gif is clicked. Currently, the ...

Cryptocurrency price tracker with sleek Bitcoin symbol and FontAwesome icons

My assignment involved creating a function that retrieves Bitcoin trades from a JSON URL, allows users to change the interval with buttons, uses fontawesome arrows to indicate rate changes (up/down/no change), and displays the data on a website. Everythin ...

Encountering ORA-01008 error while utilizing nodeOracledb in TypeScript

I am facing an issue with the result of my code. I am trying to connect a Node.js script with Oracle using TypeScript, but for some reason, an error keeps appearing in my console. I have attempted various solutions to resolve this error, but unfortunately, ...

Ways to add elements to an array nested within services and append to an object within another object

<pre lang="HTML"> <ul> <li data-ng-repeat="q in QuizObj"> <fieldset><legend>All Quizes </legend> <h1>{{q.Quiz }}</h1> <h3>options</h3> <h3>answer</h3> &l ...

Ways to ensure the express route accesses my mocked module instead of the main one when making a request to it with supertest

Struggling to simulate an uploadImage middleware function. The challenge is as follows: When making a request with supertest to /users/me/avatar in the user route, I want it to utilize the mocked uploadImage instead of the original one. Question: Where s ...

Step-by-Step Guide on Incorporating leaflet-control-geocoder into Angular 12.x

After successfully integrating Leaflet into Angular 12 using the following commands: npm install leaflet npm install @asymmetrik/ngx-leaflet npm install --save-dev @types/leaflet I made sure to include the styles: ./node_modules/leaflet/dist/leaflet.css i ...

"Looking for a datetime picker plugin that works well with Bootstrap

Check out this efficient DateTimePicker example. <head> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script> <link rel="stylesh ...

The hovering effect on the image link is causing the surrounding div to stretch too far

Whenever I hover over specific points below an image link wrapped in a div, it triggers the hovering effect for the CSS-created image link. Despite trying various solutions like overflow:hidden and display:inline-block, nothing seems to resolve this issue. ...