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.