Define a variable that triggers a function to execute after the variable has been used

When working with Express to handle routes and views using EJS template, I encountered an issue with passing values from a function. Specifically, in the following route for handling orders:

router.get('/orders/all', admin_check, (req, res) => {
  const orders = getOrders()
  console.log('----- orders obtained from function : ')
  console.log(orders)
  res.render(process.cwd() + '/src/views/admin/orders/all_orders', {
    orders: orders,
    test: 1
  })
})

The getOrders() function is used to retrieve data for 'orders'. However, despite this setup, the value returned by getOrders() seems to be undefined when passed to the EJS template.

export const getOrders = () => {
  Order.find({}, (err, orders) => {
    let ordersMap = {}

    orders.forEach(order => {
      ordersMap[order._id] = order
    })

    console.log('returning orders from function:')
    console.log(ordersMap)

    return ordersMap
  })
}

The root of the problem lies in the asynchronous nature of the getOrders() function execution within the router. The console logs placed before it are executed first, leading to 'orders' being assigned as undefined at the time of rendering. This delayed execution becomes evident through logging statements. Essentially, any manipulation prior to calling getOrders() will not impact its execution timing.

Answer №1

It seems that the issue lies in not waiting for the getOrders() function to return a response before proceeding. This is a common asynchronous behavior in Node.js.
To resolve this, you have two options: either call getOrders() with a callback function and perform your tasks within that callback, or utilize async/await while maintaining the current function structure.

If you choose to use async/await, here's how you can do it:

router.get('/orders/all', async (req, res) => {
    const orders = await getOrders()
    console.log('----- orders retrieved from the function: ')
    console.log(orders)
    res.render(process.cwd() + '/src/views/admin/orders/all_orders', {
      orders: orders,
      test: 1
    })
});

Make sure to adjust the getOrders function as follows -

export const getOrders = async () => {
     let orders = await Order.find({});
     let ordersMap = {}

     orders.forEach(order => {
       ordersMap[order._id] = order
     })
     console.log('returning orders from the function:')
     console.log(ordersMap)

     return ordersMap;
 }

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

Is my pagination in node.js using mongoose and express incorrect?

Good afternoon everyone. I have some code that seems to be functioning, but I'm worried it might not be the most efficient. Recently, I added a route to handle regex searches on my MongoDB database. The client sending the request has limitations in t ...

Using Boolean as a prop in Vue.js

Creating a Vue form to ask a question involves making a component: <template> <div class="flex flex-col items-center justify-center gap-2"> <div class="flex w-[80%] items-center justify-center gap-2 rounded-3xl p-2" ...

Refresh the page with cleared cache using window.location.reload

Is there a way to reload a page using JavaScript and still clear the cache, ensuring that the refreshed page shows the latest content from the server? It seems that other browsers are not displaying the most up-to-date versions of the content. Anyone have ...

Responsive Alignment of Slanted Edges using CSS

I have been working on creating a responsive diagonal layout with slanted shapes (refer to the image attached). However, I'm facing a challenge with aligning the edges smoothly at different screen sizes, especially when the rows grow and the screen re ...

Creating a textbox with pre-filled content

Seeking assistance with a Java compiler app I am developing through phonegap. Need help setting the default Java Class name in a textarea without it disappearing. This is what I have: <div> <label for="source">Source Code:</label> ...

Ways to invoke a controller function from a window listener function

Is there a way to trigger the close function from window.onbeforeunload even when closing the app through 'right click' -> 'close window'? It seems that this.close() is not working in this scenario, possibly due to scope issues. The ...

unable to access app.local in a routing file

So, in my express.js 4.13.3, I have set a variable called app.local in the app.js file. app.set('multimedia', __dirname + '/public/multimedia'); Now, in the routes/settings.js, I'm trying to access that variable like this: var a ...

Validating Empty Fields with jQuery

When I submit the form with empty fields, a success message appears in the dialog box. However, I want to display an error message instead. Can someone please help me find a solution? Here is my HTML code: <form id="booking" action="" method="post"> ...

I am interested in sending an email from a PDF document based on the selected check boxes

I have added a button in a PDF form that says "send an email" and I would like the form to be sent to different email addresses based on which checkboxes were selected previously. For example, there is a question about the "Size of the company" with 2 che ...

The mysterious occurrence of "Undefined" popping up in the URL of my ASP.NET application, could this be somehow linked to Google?

Several users are encountering a perplexing issue while using my web application. During their usage, they click on a button or link that redirects them to another page, but encounter a "page not found" error with a URL like: undefined I initially suspe ...

What is the best way to navigate through model data in AngularJS?

I have a dropdown populated with data from a JSON object like so: $scope.tradestyles = [ {"id":"1","source":"Source One","name":"Name One"}, {"id":"2","source":"Source Two","name":"Name Two"} ] Here is the dropdown, which utilizes select2. The ch ...

What is the best way to incorporate an image that appears when a user clicks on a

My goal is to dynamically place an image exactly where a user clicks on the webpage. Currently, I have the following code, but it only adds the image at the top and continues to do so repeatedly...not appearing at the clicked location. <html> ...

Interactive PayPal quick checkout feature

Currently, I am in the process of developing an online store for a personal project and this piece of code is extracted from my application. <div class="row"> <script src="https://www.paypalobjects.com/api/checkout.js"></script> {{#e ...

How can I remind Jade to maintain the code formatting during the compilation process?

Currently in the process of working with Jade using nodejs and express. Upon calling res.render on my jade code, it is converted to html. Nevertheless, the resulting html lacks proper line breaks. Is there a way for me to instruct jade to maintain code f ...

Is this conditional statement accurate?

Could this be a legitimate condition? Why isn't it functioning as expected in PHP? var myString = 'hello'; if(myString == ('hello' || 'hi' || 'bonjour' || 'hallo')){ alert('Welcome'); } ...

Dealing with numerous entries in an HTML form using PHP

Currently, I am learning the basics of HTML, PHP, and Javascript. I recently worked on creating a user profile form that includes fields like Full Name, Email Id, and Mobile number. I also want to incorporate a section for "Hobbies/Interests" where users ...

Master the art of customizing SweetAlert designs!

Can anyone provide guidance on how to style the AJAX response data in SweetAlert? Below is my code and a sample image. Any assistance would be greatly appreciated. Order screenshot swal({ title: "Confirm your transaction", html:true, showSpinner: ...

Developing a Cloud Function for Stripe that is taking forever to finalize writing data to Firestore

Currently, I am facing an issue with my Google Cloud function (provided below) that handles webhooks from Stripe payments and stores some data in Firestore. The problem is that it seems to hang for approximately 3 minutes before completing. const Stripe = ...

Is there a way to evenly space out the buttons in the Nav element with more room in between each one?

I need the buttons to be evenly spaced with more room between them. And, of course, they need to be responsive in the end. I attempted to use Bootstrap's "d-flex" class to arrange the buttons, but it didn't work as expected. If you review my Boo ...

Detect the initial collision exclusively (Collision detection using raycasting)

I am currently working on a never-ending runner game where a character is positioned at (0,0) and can only move along the X-axis by using arrow keys or the mouse. There are two different types of objects moving from z = -10000 towards the character, and on ...