Linked Questions

Popular Questions

I am new to the asynchronous and web application development and i cannot figure out a way to return data from a function before my page is rendered. Also new to sequelize and any feedback on formatting or best practices is appreciated.

I have tried setting this function as a route which in fact does return data if i send it as a response res.send(recipes). But i want it to act as a function that i can call before my page gets rendered

getRecipes.js

const sequelized = require('sequelize'); 
const op = sequelized.Op;

async function getRecipes(){
    //SELECT * FROM ingredients
    ingredients.findAll({ 
        where: {}, 
        raw : true 
    }) 
    .then(ingredients_result =>{ 
        //Get ingredient that expires soon
        //Find recipes of the ingredient that expires soon
        recipe_ingredient.findAll({ 
            where: {}, 
            raw: true 
        }) 
        .then(recipe_ingrdient_result =>{ 
            //If we have all ingredients for a recipe then find name of that recipe by ID
            recipes.findAll({ 
                where: {recipe_id: {[op.in]: suggested_recipes}} 
            }) 
            .then(recipes =>{
                someinfo = JSON.stringify(recipes);
                // This is where i need the date to be returned from
                return someinfo; // But every time i load a page this returns undefined
            }) 
        })
    })
}

module.exports.getRecipes = getRecipes;

routes/user.js

const getStuff = require('./getRecipes');
router.get('/dashboard', async function(req, res){
    //This returns undefined
    var r_name = await getStuff.getRecipes();
    res.render('dashboard',{
            title:"Dashboard",
        });
    })

I am probably misunderstanding how async works, so any help would be appreciated! I know want to be able to retrieve results by running getRecipes function before the page gets rendered.

Related Questions