the pause in execution before my function redirects to a different route

Currently, I am developing a page using nodeJs with express which is supposed to display a table. However, I encountered an issue with my variable "allMusique" that contains the data for my page. When trying to access it initially, there seems to be an error. But strangely, when I refresh the page once, everything shows up correctly with all the data displayed. Can anyone identify what might be the problem here?

Below is the snippet of my code:

var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
var allMusique;
var idMaxMusique;

router.get('/', function(req, res, next) {
    function getAllMusique(){
        MongoClient.connect(url, function(err, db) {
            if (err) throw err;
            var dbo = db.db("projet_node");
            dbo.collection("musiques").find({}).toArray(function(err, result) {
                if (err) throw err;
                allMusique = result;
                var size = allMusique.length-1;
                idMaxMusique = parseInt(result[size].id)+1;
            });
        });
    }

    getAllMusique();
    res.render('musiques', { resultat: allMusique, idMax: idMaxMusique });
});

module.exports = router;

Answer №1

When you first call res.render, the variable allMusique is not yet set because it did not wait for the database access to finish. On the second attempt, it is already populated due to the initial database access.

I suggest calling res.render inside the Mongoclient.connect function.

router.get('/', function(req, res, next) {
    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        var dbo = db.db("projet_node");
        dbo.collection("musiques").find({}).toArray(function(err, result) {
            if (err) throw err;
            allMusique = result;
            var size = allMusique.length-1;
            idMaxMusique=parseInt(result[size].id)+1; 
            res.render('musiques', { resultat: allMusique, idMax: idMaxMusique });
        });
    });
});

If you want to maintain the structure, you can convert the res.render into a function callback.

function getAllMusique(callbackFunction){
    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        var dbo = db.db("projet_node");
        dbo.collection("musiques").find({}).toArray(function(err, result) {
            if (err) throw err;
            allMusique = result;
            var size = allMusique.length-1;
            idMaxMusique = parseInt(result[size].id)+1;
            callbackFunction();
        });
    });
}

getAllMusique(()=>res.render('musiques', { resultat: allMusique, idMax: idMaxMusique }));

Alternatively, you can make the function return a promise once the data has been retrieved and set.

function getAllMusique(){
    return new Promise((resolve, reject) => {
        MongoClient.connect(url, function(err, db) {
            if (err) throw err;
            var dbo = db.db("projet_node");
            dbo.collection("musiques").find({}).toArray(function(err, result) {
                if (err) throw err;
                allMusique = result;
                var size = allMusique.length-1;
                idMaxMusique = parseInt(result[size].id)+1;
                resolve();
            });
        });
    });
}

getAllMusique().then(()=>res.render('musiques', { resultat: allMusique, idMax: idMaxMusique }));

Answer №2

retrieveAllSongs is a promise-based function. Simply shift the rendering process inside the callback for optimal performance.

Answer №3

Another approach to solving this issue involves using async/await.

router.get('/', async function(req, res, next) {

//...

await getAllMusique();
res.render('musiques', { resultat: allMusique, idMax: idMaxMusique });

}

It's worth noting that the callback in .get() is now marked as async, enabling you to use await with your function.

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 JQuery mobile navigation menu effortlessly appears on your screen

I am experiencing an issue with a JQuery mobile navigation that is designed for screens @979 pixels wide. The problem arises when the screen is resized to 979px - the menu pops up fully extended and covers the content of the web page. I suspect that this ...

By default, use jQuery to load the content of a div

Upon page load, I am looking to display the content within #destiny2. This section includes text and images, as well as additional content for three categories. Initially, the first category should be shown without requiring a click. Subsequently, clicking ...

What steps should be taken to fix the sinopia installation error?

While operating on redhat5.9, I encountered an exception related to 'make'. I am curious about what they are trying to create. It seems like it's related to JavaScript. [root@xxxx bin]# npm install -g sinopia --python=/usr/local/clo/ven/pyt ...

Issues encountered while loading the Tensorflow.js model in a bootstrap webpack demonstration

I've been working on loading a JSON-formatted model in Tensorflow.js using the Bootstrap webpack example from GitHub. Initially, when I used Tensorflow.js without bootstrap in webpack, the code worked perfectly either in webpack or if I included it v ...

Interacting with iView UI dropdown menu items

I'm attempting to create a click event in iView ui. Here's my code: <DropdownMenu slot="list"> <DropdownItem @on-click="markAsRead">Mark as read</DropdownItem> </DropdownMenu> The function markAsRead isn't exec ...

Trigger the Material UI DatePicker to open upon clicking the input field

I have a component that is not receiving the onClick event. I understand that I need to pass a prop with open as a boolean value, but I'm struggling to find a way to trigger it when clicking on MuiDatePicker. Here is an image to show where I want to ...

Replace HTML elements with AJAX and JavaScript

Working with MySQL data in pyramid presents a challenge as I need to dynamically change an HTML if statement based on the results from JS ajax calls. The main page receives data from views.py and passes it to the .mak script. The key views here are the ma ...

Unable to load the threejs module

I am still learning about threejs and have mostly worked on projects using a dev server (vite) locally. This setup limited me to accessing my projects only from the browser on my computer. Here is how I typically include my files in these projects: <bod ...

Integrating Google Sheets in an Express.js application involves syncing data

Is it possible to implement a feature in Express JS that allows users to authorize their Google account with our app? This way, we can access the google sheet from their accounts and display it within our express app. If users make changes to the spreadshe ...

Troubleshooting issue with the spread operator and setState in React, Typescript, and Material-ui

I recently developed a custom Snackbar component in React with Material-ui and Typescript. While working on it, I encountered some confusion regarding the usage of spread operators and await functions. (Example available here: https://codesandbox.io/s/gift ...

How can one utilize JSON.parse directly within an HTML file in a Typescript/Angular environment, or alternatively, how to access JSON fields

Unable to find the answer I was looking for, I have decided to pose this question. In order to prevent duplicates in a map, I had to stringify the map key. However, I now need to extract and style the key's fields in an HTML file. Is there a solution ...

What is preventing me from utilizing require in vue-router's routes.js file?

Vue-router typically requires the standard setup as outlined below: In main.js, the routes.js file is required and it usually contains code similar to this: //routes.js import Register from './components/Register' import Login from './comp ...

I encountered an issue with Array map when attempting to access the data during a dynamic rendering process

function UserTransactionsComponent1() { const [accounts, setAccounts] = useState(); useEffect(() => { async function fetchData() { const res = await fetch( 'https://proton.api.atomicassets.io/atomicassets/v1/accounts' ...

Having trouble importing AnimeJS into an Ionic-Angular project

I successfully added AnimeJS to my Ionic 4 project using the commands below: npm i animejs --save npm i @types/animejs --save To reference AnimeJS, I used the following import statement: import * as anime from 'animejs' However, whenever I tr ...

Fluctuate the window.location with jQuery or javascript

My goal is to create a functionality where clicking an image will toggle the window.location url between '#' and '#footer'. The current code I have for this is: <script> function clickarrow(){ var rd=Math.floor(Math.random() ...

Ensuring continuous execution of JS EventListener

The other day, I received a solution from someone on this platform for a script that changes the color of a div when scrolling. Here is the code I implemented: const x = document.getElementById("menuID"); window.addEventListener("scroll", () => { ...

Retrieve the contents of the browser's DOM from within an Android operating system runtime

Imagine a typical login page similar to the one depicted below: https://i.stack.imgur.com/SF1Bd.jpg To interact with the HTML elements within the DOM, we can utilize either jQuery or conventional JavaScript like so: https://i.stack.imgur.com/e5aQZ.png ...

Extract all links from an external website

I'm attempting to extract all the URLs from a webpage using jQuery so that I can later use them with $.get(). If these URLs were located on the same page as the script, retrieving them would be easy by doing something like var links = document.getEle ...

What is the best way to transfer the content from a tinyMCE textarea editor to an inner controller using Symfony3 and Ajax

I have two small rich text editors identified as #homepage and #thankyoupage. My goal is to submit the content of these TinyMCE text areas to a Symfony controller. Below is my front-end implementation: https://i.stack.imgur.com/TE1Ys.jpg Currently, I am ...

Using Three.JS 'OrbitControls' in VueJS application results in a black screen appearing?

Currently, I've been delving into the basic cube exercise on Three.js, and incorporating the three.js cube into my Vue.JS application. Initially, everything was functioning smoothly, with my cube rotating as intended using animate, etc. However, thi ...