javascript - 如何从嵌套的 Promise 中接收数据
问题描述
我在 Sequelize 中定义了 2 个使用一对多关系关联的模型,然后使用 Sequelize 实例填充数据库。
Connection = new Sequelize({...});
Const Recipe = Connection.define('recipe', {name: Sequelize.STRING})
Const Ingredient = Connection.define('ingredient', {name: Sequelize.STRING})
Recipe.hasMany(ingredients);
Ingredient.belongsTo(Recipe);
_.times(3, () => {
return ProteinRecipe.create({
name: `SOMENAME`})
.then((recipe) => {
_.times(3, () => {
return recipe.createIngredient({
name: `INGREDIENT FROM :${recipe.name}`
})
我想做的是从所有食谱中检索所有成分数据。
我努力了
const readWithPreferences = (req, res) => {
Recipe.findAll()
.then((recipes) => {
return Promise.all(recipes.map((recipe) => {
let recipeObj = {};
recipeObj.info = recipe.dataValues;
recipeObj.ingredients = [];
recipe.getIngredients()
.then((ingredients)=>{
return Promise.all(ingredients.map((ingredient)=>{
recipeObj.instructions.push(ingredient.dataValues);
}));
});
return recipeObj;
}))
.then((recipesArray) => {
let responseObj = {};
responseObj.data = recipesArray;
res.status(200).send(responseObj);
})
});
}
当我检查内部承诺调用中是否正在访问数据时,记录器正在显示数据。但我只收到来自外部承诺数组的信息。如何从内部承诺数组返回数据?
解决方案
您没有在外部 Promise.all 回调中返回内部承诺。
const readWithPreferences = (req, res) => {
Recipe.findAll().then(recipes => {
return Promise.all(recipes.map(recipe => {
let recipeObj = { info: recipe.dataValues }
return recipe.getIngredients()
.then(ingredients => {
recipeObj.instructions = ingredients.map(i => i.dataValues)
// now, return the whole recipe obj:
return recipeObj
})
}))
})
.then(data => {
res.status(200).send({ data })
})
}
推荐阅读
- python - SampleRNN - Pytorch 实现初学者
- superset - 无法在 Windows 10 上安装 Apache SuperSet - 在步骤 11/32 失败:RUN cd /app/superset/assets && npm run build && rm -rf node_modules
- javascript - 创建像 frontierwithin.thorne.com 这样的背景动画
- ios - 如何在 Swift 5 中将电子表格数据预加载到 Core Data?
- javascript - 如果当前路径位于任何有效路由上,React 路由器仅显示导航组件
- php - PRG 多张图片上传 => 修复临时文件夹中缺少的图片时出现问题
- python - 如何将带有 String(number) 条目的列表转换为带有可与 numpy.dot (dotproduct) 一起使用的数字的列表
- python - 如何制作随机电子邮件生成器?
- in-app-purchase - App Store Connect 未显示所有销售额 - 为什么?
- css - 如何为 Gridsome/vue.js 中的不同页面指定不同的背景颜色?