Leveraging Promises in a for loop

My current approach involves iterating through a range of dates to find the top song for each date using a for loop. I call a function within this loop to search my database for the top song, and I wrapped it in a promise to prevent it from interrupting the loop. However, this method doesn't seem to be working as expected. Can anyone suggest a better solution to tackle this issue?

app.post('/getDate', function (req, res) {
      this.tracks = [];
      let until = new Date(req.body.dateToOutput);
      for (var d = new Date(req.body.dateFromOutput); d <= until; d.setDate(d.getDate() + 1)) {
            date = d.toLocaleDateString('en-US', { timeZone: 'UTC' });
            console.log('date', date);
            new Promise(function (resolve, reject) {
                  getDate(date).then(() => {
                        resolve();
                  })
            });
      }
      console.log(this.tracks);
});
function getDate(date) {
      return new Promise(function (resolve, reject) {
            Track.find({ Date: date }, function (err, track) {
                  if (!err) {
                        console.log(track);
                        this.tracks.push(track);
                        resolve();
                  }
                  else {
                        reject();
                  }
            }).sort({ Streams: -1 }).limit(1);
      });
}

Answer №1

It appears that the promise is not being executed, and there seems to be a reference to an undefined object in your getDate function. Additionally, the for loop does not wait for a promise to be resolved or rejected. Consider the following:

new Promise(function (resolve, reject) {
    getDate(date).then(() => {
        resolve();
    })
});

While you are creating a new promise, it is never actually being called.

In the getDate function, you are referencing an object that does not exist within its context:

this.tracks.push(track);

This will result in errors because this.tracks is not a part of the getDate function but rather an anonymous function called by the app.post method.

Instead of directly pushing something into this.tracks, you should return the track itself:

if (!err) {
    console.log(track);
    resolve(track);
}

Using async-await can help pause the loop until a promise is resolved or rejected. As such, your anonymous function should now be an async function to utilize await. Additionally, there is no need for wrapping a promise inside another promise as shown in this code snippet:

new Promise(function (resolve, reject) {
    getDate(date).then(() => {
        resolve();
    })
});

A simpler approach suffices:

getDate(date).then(() => {
   resolve();
})

Since the getDate() function already returns a promise.

After implementing these modifications, your code takes the following shape:

const response = app.post('/getDate', async function (req, res) {
      this.tracks = [];

      let until = new Date(req.body.dateToOutput);
      for (var d = new Date(req.body.dateFromOutput); d <= until; d.setDate(d.getDate() + 1)) {
            date = d.toLocaleDateString('en-US', { timeZone: 'UTC' });
            console.log('date', date);
            const ctrack = await getDate(date);
            this.tracks.push(ctrack);
      }

      console.log(this.tracks);
      return this.tracks;
});

function getDate(date) {
      return new Promise(function (resolve, reject) {
            Track.find({ Date: date }, function (err, track) {
                  if (!err) {
                        console.log(track);
                        resolve(track);
                  }
                  else {
                        reject();
                  }
            }).sort({ Streams: -1 }).limit(1);
      });
}

As the response from an async function returns a promise, you can handle and use the response with then and catch like so:

response.then(trackList =>{
   console.log(trackList);
}).catch(()=>{
   console.error("something went wrong...!");
})

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

The input field inside the div disappears when the mouse leaves

I need to create a div that remains visible as long as the mouse hovers over it, but disappears when the mouse moves off. Additionally, I want a sign-up form to appear on hover and disappear once the sign-in process is complete. Check out the jsFiddle Demo ...

Refreshing directive function following a POST request with Angular JS

I am currently working on an open-source application that utilizes AngularJS for the frontend. The app has a unique structure where it manipulates the DOM by deleting and adding content for security reasons. However, I have encountered a challenge that I a ...

Query all users from mongoDB based on their proximity

Looking to retrieve all users based on their distance using mongoDb? You can use the "nearSphere" feature for this purpose: { $nearSphere: { $geometry: { type : "Point", coordinates : [ <longitude>, <latitude> ] }, ...

The design elements are not being implemented on my custom React library built with TypeScript

I recently created a React library called https://github.com/deadcoder0904/react-typical/ and added styles to the component in the examples/ directory. However, I've noticed that the styles are not being applied. Below is the content of the example/i ...

Encountering the issue of "unable to retrieve" when attempting to create an API in Express.js

I am currently developing a REST API using express js, but I encountered an issue with the error message "Cannot GET /api/bears". Here is my code snippet: server.js var express = require('express'); var app = express(); var bodyParser = require ...

Exploring cookie management in AngularJS using the $http service

Currently, I am facing a challenge in implementing authentication using ExpressJS' cookie sessions and AngularJS. The issue I am encountering is that even though I have managed to get ExpressJS to send session cookies, Angular does not send them with ...

What strategies can I employ to optimize this code in RXJS and Angular?

Is it possible to streamline these nested arrays for more efficient execution after all subscriptions have been completed? I believe there may be a solution involving the use of pipes, mergeMaps, concatMaps, etc. this.teams = [ { Assignments: [{Id: ...

The issue of selecting multiple classes simultaneously is not being resolved

Here is my JavaScript code snippet: $('.normal-box').click(function(){ //unique row id var id = $(this).data('row-id'); //its index according to the content array var index = $(this).data('index'); //which car ...

Having trouble loading services within my Angular controller

After developing my Angular application, I added some basic code to my controller which is displayed below. Now, I am attempting to include two services that I created in my services.js file. This file is being loaded in my index.html and required within m ...

The issue of banding caused by Bloom and Antialiasing in Three.js rendering

I'm attempting to incorporate a glowing effect into my scene. To achieve this, I understand that using a bloom filter with the EffectComposer is the ideal approach. However, I've encountered an issue where utilizing the EffectComposer compromises ...

Is there a way to retrieve table cell data in Javascript or jQuery without specifying an id or class?

Can someone assist me in retrieving data from table cells? The cell data contains valuable information that requires the use of either JavaScript or jQuery. I aim to insert this data into a MySQL database. Your help with this issue would be greatly apprec ...

Canvas: add a translucent layer covering the entire canvas, leaving one window untouched

I'm working on a project where I have a rectangular canvas with an image on it. I want to implement a cool effect where, as the user hovers over the canvas, the whole canvas becomes semitransparent - except for a small rectangle around the cursor whic ...

Making a standard AJAX request using jQuery without including the XHR header

I am looking to make an ajax-type request using the following headers (or something similar): GET example.com/ajaxapi/article/1 HTTP/1.1 Host: localhost Accept: application/hal+json Cache-Control: no-cache The key aspect here is to accomplish this withou ...

The Ajax request returned a status of 200, yet an error message was displayed

Even though the status is 200, why does it print the error message inside alert("error...");? function makeSelect() { var blouseoption = document.querySelector('input[name="blouseoption"]:checked').value; var url = "http://dukano.co/sakh ...

Is there a way to incorporate unique shapes into mxGraph?

What is the process for including custom shapes in mxgraph? Image Representation of Shapes Check out these BPM shapes ...

The server returned a response that was void of any content

I have encountered an issue while trying to retrieve data from my server. The request works perfectly fine when tested with Postman, returning the expected data. However, upon implementing the request in my application, I receive an empty object with prope ...

Setting the $dirty flag to true when a value is entered in the text box, but not the other way around

When I enter a value in the text box, myForm.$dirty gets set to true. However, the flag does not revert back to false when I delete all values from the text box. Why is this happening and how can I fix it? <input name="input" ng-model="myModel.text"& ...

Are your JavaScript scripts causing conflicts?

My bootstrap Carousel was working perfectly fine until I added a script to modify the navigation bars. The original script for the Carousel looked like this: <script> !function ($) { $(function() { $('#myCar ...

The console is showing an Error [ERR_HTTP_HEADERS_SENT] because headers cannot be set after they have already been sent to the client

I'm struggling to figure out how to resolve this issue. Interestingly, when I use PostMan to send data, everything is saved successfully and the task is completed without any problems. However, I see this error in the console. If I remove the .json(t ...

How to handle the lack of support for the 'assign' method in IE?

My JavaScript/Babel script is working perfectly in Chrome and Firefox, but it's giving me trouble in Internet Explorer 11. I'm seeking assistance from someone who might be able to help. Below is the function causing the issue: getDaysWithEvent ...