The promise was made but the function was never carried out

exports.index = function(req, res) {
   moviedb.indexMovie().then(function(){
       console.log("DATABASE VALUES READ SUCCESSFULLY");
  }); 
};

var moviedb = module.exports = {
indexMovie : function() {
        return new P(function(resolve, reject){
                                MovieEntry.removeAsync({})
                                .then (function() {
                                    return P.map(movieJson, x => movieApi.searchMovies(x.name)).map(x => {
                                         return new MovieEntry({
                                             id: x.id,
                                             title : x.title,
                                             originalTitle : x.originalTitle,
                                             year : x.year,
                                             popularity : x.popularity,
                                             voteAverage : x.voteAverage,
                                             votes : x.votes,
                                             isAdult : x.isAdult,
                                             video : x.video,
                                             poster : x.poster,
                                             backdrop : x.backdrop,                        
                                         });
                                     }).map(x => x.save())
                                       .then(x => console.log("All tasks completed successfully!"))
                                       .catch(e => { console.error("An error occurred", e); throw e; });
                                    })
                            })
                    }       
                } 

I am encountering an issue where the log "DATABASE VALUES READ SUCCESSFULLY" is not being displayed. Despite this, the indexMovie function runs without any errors. Can someone advise me on what might be causing this? I am uncertain about how promises work in this context and want to make sure that I can read from the database after the write operations are complete.

Answer №1

It's unnecessary to create a new promise when you already have one in place. This practice is known as the deferred antipattern, which is detailed here.

The best approach is to utilize the existing promise from the removeAsync() function and allow the promise chain to execute normally.

exports.index = function(req, res) {
   moviedb.indexMovie().then(function(){
       console.log("READING VALUES FROM DATABASE");
  }); 
};

var moviedb = module.exports = {
    indexMovie : function() {
            return MovieEntry.removeAsync({})
                .then (function() {
                    return P.map(movieJson, x => movieApi.searchMovies(x.name)).map(x => {
                         return new MovieEntry({
                             id: x.id,
                             title : x.title,
                             originalTitle : x.originalTitle,
                             year : x.year,
                             popularity : x.popularity,
                             voteAverage : x.voteAverage,
                             votes : x.votes,
                             isAdult : x.isAdult,
                             video : x.video,
                             poster : x.poster,
                             backdrop : x.backdrop,                        
                         });
                     }).map(x => x.save())
                       .then(x => {console.log("Process Completed!"); return; })
                       .catch(e => { console.error("An Error Occurred", e); throw e; });
                    });                     
                }       
} 

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

disable any other active toggle in a vue component

Exploring JavaScript and how to accomplish the following tasks Snapshot The issue I am facing is that if I click on a product, and then click on settings, both are open. However, I want only the currently clicked toggle to be open. For instance, if I cl ...

Unusual occurrence while creating a unique identifier for a React component

I am working on creating a unique identification number for each React component, which will be assigned to the component upon mounting. Here is the approach I am taking: The callOnce function is used to ensure that a specific function is only executed on ...

In Javascript, the difference between defining a variable using "this.varName" and "var varName" lies in the scope of the variable

Excuse my JS ignorance, but here's a question: In JS, I've noticed functions that define variables inside them like this: function functionName(){ this.something = ""; }; I'm wondering if something is considered a local variable. W ...

"How can I exclude empty fields from the form.serialize function in jQuery when using php?" is not functioning as expected

I am facing an issue with using How do I use jQuery's form.serialize but exclude empty fields. Despite following a minimal example that directs to a php script: <html><head> <script src="jquery.min.js"></script> <script typ ...

Optimal Method for Organizing Items in Express.js Using Mongodb

Can you share your insights on the best practices for sorting objects in expressjs + mongodb(mongoose) web applications? Imagine we have a Product model with four attributes: var ProductSchema = new mongoose.Schema({ name: String, // "Summer T-sh ...

What is the solution to the error "Maximum update depth exceeded. Calls to setState inside componentWillUpdate or componentDidUpdate" in React?

Everything was running smoothly until this unexpected issue appeared. I attempted to change the condition to componentDidMount, but unfortunately, that didn't resolve the problem. The error is occurring in this particular function. componentDidUpd ...

How do you obtain the string name of an unknown object type?

In my backend controllers, I have a common provider that I use extensively. It's structured like this: @Injectable() export class CommonMasterdataProvider<T> { private readonly route:string = '/api/'; constructor(private http ...

Encountering [object, Object] while attempting to display JSON object retrieved from req.body in the console

While attempting to insert a product's details into my API's PostgreSQL database using Postman, I encountered an issue where the values of the specs key were displayed as [object Object] instead of showing the complete data. As a result, even in ...

Tips for configuring page-specific variables in Adobe DTM

Although I have integrated Adobe Analytics for tracking on my website, I am facing difficulty in properly defining the variables. This is how I attempted to define the variable: var z = new Object(); z.abc = true; z.def.ghi = true Despite following the ...

Encountering a 401 Error while trying to host an Angular app on Google Cloud Storage

I am currently facing an issue with deploying my Angular app to a Google Cloud Storage bucket. The bucket is public and set up to be served as a custom website via CNAME (test.example.com). The main page and 404 handler are mapped to index.html, but I am e ...

What are some ways I can make my content come alive on my website using the Tympanus examples

After spending hours searching for a way to add animation to my content, I finally found a technique that seemed promising. Despite following the same steps as outlined in the tutorial I found, I was disappointed to discover that there was no animation o ...

Managing mouse click events in jQuery

Here on SO, I successfully implemented the mouse down handler. Now, my goal is to separate these functions into their own file named test.js. Within test.js, the code looks like this: function handleMouseDown(e) { console.log('handleMouseDown&ap ...

Is there a way to showcase a block of Python code using a combination of HTML, CSS, and Javascript to enhance its

On my website, I want to display code blocks similar to how StackOverflow does it. The code block should be properly colored, formatted, and spaced out for better readability. All the code blocks on my site will be in python. def func(A): result = 0 ...

What causes directive templates to be fetched from the server at times (resulting in a 304 response), while other times they are retrieved from the browser cache without

I've noticed that when I reload the page, Angular directive templates load in two different ways. The first way is when the browser sends a request to the server and receives a 304 response - everything works fine. However, the second way is puzzlin ...

Unable to insert an array within a function

I've searched for the answer but couldn't find it - my array is not pushing to datahasil. How can I push the array hasil into datahasil...?? const data1 = await JadwalBooking.aggregate([{ $project: { "keterangan": "$keterangan", ...

Using jQuery to update a specific item in a list

My current project involves developing an Image Gallery app. It uses <img> tags within li elements. The code snippet is as follows: var $slideR_wrap = $(".slideRoller_wrapper"); var $slidesRoller = $slideR_wrap.find(".slidesRoller"); var $slideR ...

Error encountered while using XLSX.write in angular.js: n.t.match function is not recognized

I've encountered an issue while trying to generate an .xlsx file using the XLSX library. The error message I received is as follows: TypeError: n.t.match is not a function at Ps (xlsx.full.min.js:14) at Jd (xlsx.full.min.js:18) at Sv (xlsx.full.min ...

Mobile version experiencing issue with Navbar not collapsing

The dropdown navigation bar on the mobile version of my website is not functioning properly. Despite several attempts, I have been unable to figure out a way to make it work effectively. <!DOCTYPE html> <html lang="en"> <head> & ...

The React getTime() method does not properly update the state

I am attempting to update the state of the component Demoss using an external function called getTime(). My goal is to start updating the time in the state time when the page loads. In order to achieve this, I have called it in the componentDidMount meth ...

Decoding JSON data with JavaScript

My JavaScript code is giving me trouble. I am using an ajax method that returns a JSON string like this: { "ObjectResponse": { "Operation": "OK", "Response": "SUCCESS", "Message": "List of AAA Found", "List": [ { "keySourc ...