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

Troubles arise when attempting to utilize yarn for my projects

Whenever I enter the command yarn start in the terminal, I get this output: yarn run v1.22.4 $ react-scripts start 'react-scripts' is not recognized as an internal or external command, operable program or batch file. error Command fai ...

How can I access and modify objects within a state array in reactJS when using the setState() method?

Upon reviewing my code, I came across the following declaration: constructor(props) { super(props); this.state = { productArray: [{ barcode: '', name: '' }], numberOfRecords: ...

The ActivatedRoute.routeConfig object appears to be empty in an Angular 2 project built with Angular-cli

Two projects I've created using angular-cli are working perfectly fine. However, in one of them, the routeConfig is showing as null and I can't figure out what's causing this issue. Both projects have identical package.json files, so there ...

Experiencing difficulty adjusting the width of a Tumblr post with JavaScript or jQuery?

Calling all coding experts! I've been working on customizing a Tumblr theme, and everything is looking good except for one issue. I'm struggling to adjust the width of photos on a permalink (post) page. Check out this link: You'll notice t ...

How can I create a script in Discord.js that automatically sends users their information upon joining the server?

I'm currently working on developing a code that automatically sends the user's avatar, username, ID, account creation date, server join date, and status when they join The structure of the code looks something like this: module.exports = (Discor ...

Unable to interact with a button through JavaScript using execute_script in Selenium

https://i.stack.imgur.com/hJmtK.png I am attempting to remove a cookies popup by accepting the cookies and clicking confirm. While I am able to click an input labeled "zgadzam się na", for some reason, clicking a button with the label "potwierdź" appears ...

Access user connections through Discord.js bot

Hi there, I'm currently working on creating a bot that can retrieve a user's connected battle.net account and display their game rank. I am utilizing the discord.js library and have been attempting to access the UserProfile through the bot. Unfor ...

Unlocking the Secret: How to Bind a Global Touch Event Handler in Angular 4 to Prevent iOS Safari Page Drag

The issue at hand is that within my Angular 4 application, there is a D3.js chart that relies on user touch input for dragging a needle to a specific value. The drag functionality is triggered by 'touchstart', while the registration of the final ...

What is the best way to implement promise function in a JavaScript functional method such as forEach or reduce?

I have implemented a promise function in the following way: // WORK let res = {approveList: [], rejectList: [], errorId: rv.errorId, errorDesc: rv.errorDesc}; for (let i = 0; i < rv.copyDetailList.length; i ++) { const item = rv.copyDetailList[i]; ...

Unable to locate module '.next/server/font-manifest.json'

I'm encountering a frustrating issue while attempting to deploy my nextjs app with server rendering. The app was created using Azure Pipelines and then uploaded to a production server that runs on a Linux operating system. Below is the configuration ...

Is it possible to pass a parameter to a PHP controller using JavaScript without relying on jQuery or AJAX?

Is it possible to achieve the task at hand? That's the main question here. My goal is to extract data from a popup window and then, upon closing it, send this extracted content to a PHP controller for further processing. I'm facing conflicts wi ...

The webpage is unreachable on localhost after attempting to write to a file using node.js

I'm currently attempting to update a file using Node.js. I have a form that contains checkboxes, and upon form submission, the server should update the file based on which checkboxes are selected: a, b, or c. The JSON file structure is as follows: { ...

When using Selenium WebDriver to locate an object, an error may occur stating that the result of the xpath expression is "[object Text]" instead of an element as expected

I am currently utilizing Selenium to validate the existence of specific text within a web page. Here is an example of how the HTML appears. <html> <div class="a-content"> <!--!-->==$0 " Text to Locate" <b ...

AngularJS's support for html5mode on GitHub pages is now available

Is it feasible for GitHub pages to accommodate AngularJS in html5mode? I came across a source online suggesting that it can be done with a fallback page for 404 errors. However, this solution seems flawed as it may result in multiple 404 errors, which wou ...

Execute the JavaScript callback

I am encountering an issue when trying to pass an anonymous function as a callback and call it. I seem to be missing something simple, because I keep getting the error 'Uncaught type error - callback is not a function'. Here is what I am attempti ...

Having difficulty utilizing the express.session module in conjunction with HTTPS

I need to implement authentication and session creation on a HTTPS static website using expressjs. Here is the code snippet: app.js: // Set up the https server var express = require('express'); var https = require('https'); var http ...

HTML- Any suggestions on how to troubleshoot my sticky navbar not functioning properly?

I'm having trouble creating a sticky navbar. I've attempted to use z-index: 999 but it's not behaving as expected. * { margin: 0; padding: 0; } .navbar { display: flex; align-items: center; justify-items: center; position: ...

The issue with displaying inline block is that the divs are not appearing side by side on the

Two of my div elements, namely form-panel and data-panel, are currently not aligned on the same line. How can I use display:inline-block to align them in a single line? Please review the code provided below. I have already used display:inline-block on both ...

setting a callback function as a variable

I have encountered an issue where I am passing a callback function but unable to call it when the onreadystatechange changes its value, specifically request.onreadystatechange = func. Even though I receive a response from the server when making the ajax ...

the deactivation of my rollover class is being caused by my float class

With the assistance of a generous contributor on stackoverflow, I was able to overlay different colored CSS boxes onto various images. These boxes could be removed upon mouseover, revealing the images beneath. You can view the code I used on fiddle here. ...