Javascript 等待来自链接sequelize函数的异步响应

Javascript 等待来自链接sequelize函数的异步响应,javascript,node.js,express,sequelize.js,Javascript,Node.js,Express,Sequelize.js,我不熟悉异步和web应用程序开发,在呈现页面之前,我无法找到从函数返回数据的方法。同样是新的续集,任何关于格式或最佳实践的反馈都将不胜感激 我尝试将此函数设置为一个路由,如果我将其作为res.sendrecipes响应发送,它实际上会返回数据。但我想让它充当一个函数,在呈现页面之前可以调用它 getRecipes.js const sequelized = require('sequelize'); const op = sequelized.Op; async function getRe

我不熟悉异步和web应用程序开发,在呈现页面之前,我无法找到从函数返回数据的方法。同样是新的续集,任何关于格式或最佳实践的反馈都将不胜感激

我尝试将此函数设置为一个路由,如果我将其作为res.sendrecipes响应发送,它实际上会返回数据。但我想让它充当一个函数,在呈现页面之前可以调用它

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",
        });
    })

我可能误解了async的工作原理,所以如果有任何帮助,我将不胜感激!我知道您希望能够通过在呈现页面之前运行getRecipes函数来检索结果。

首先,如果您已将函数设置为异步,请使用它:

以下是在代码中使用async/await的方式:

async function getRecipes() {
    //SELECT * FROM ingredients
    let ingredients_result = await ingredients.findAll({ // <------- CHANGE IS HERE
        where: {},
        raw: true
    });

    //Get ingredient that expires soon
    //Find recipes of the ingredient that expires soon
    let recipe_ingrdient_result = await recipe_ingredient.findAll({ // <------- CHANGE IS HERE
        where: {},
        raw: true
    });

    //If we have all ingredients for a recipe then find name of that recipe by ID
    let recipes_result = await recipes.findAll({ // <------- CHANGE IS HERE
        where: {
            recipe_id: {
                [op.in]: suggested_recipes
            }
        }
    })

    let someinfo = JSON.stringify(recipes_result);
    return someinfo; 
}

getRecipes没有返回任何内容。更改为返回配料。findAll。。。还可以返回配方和配料。findAll。。。尽量避免承诺,因为回调反模式可能的重复不是重复。我可能误解了异步的工作原理——首先,您在承诺方面有问题。你没有把承诺很好地连锁起来。从那以后一定要回来。除非必要,否则不要嵌套。您也不会处理中间件中的错误。我知道这对您中的一些人来说可能很简单,但从同步切换到非同步并不容易,但感谢您的反馈。