gpt4 book ai didi

javascript - 如何从嵌套 Promise 接收数据

转载 作者:行者123 更新时间:2023-12-03 01:34:54 25 4
gpt4 key购买 nike

我在 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 调用中是否正在访问数据时,记录器正在显示数据。但我只接收来自外部 promise 数组的信息。如何从内部 promise 数组返回数据?

最佳答案

您没有在外部 Promise.all 回调中返回内部 promise 。

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 })
})
}

关于javascript - 如何从嵌套 Promise 接收数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51118116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com