我是新来的异步和Web应用程序开发,我无法想出一个办法,我的网页呈现之前从一个函数返回的数据。此外新作sequelize和格式化或最佳做法的任何反馈意见表示赞赏。
我曾尝试设置此功能为这实际上不会返回数据,如果我把它作为响应res.send(配方)的路线。但我想它作为我的网页被呈现之前,我可以调用一个函数
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;
路线/ 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",
});
})
我可能误解了如何异步工作,所以任何帮助,将不胜感激!我知道希望能够通过运行getRecipes功能的页面获取呈现之前检索结果。
首先,如果你所做的功能async
然后用它(DO READ):
这就是你应该在你的代码中使用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;
}