【发布时间】:2019-01-19 16:24:18
【问题描述】:
我有一个带有 Sequelize/mysql 的 react/node/express 应用程序。使用 Axios 进行 API 调用。
我需要做什么:
- 将配方发布到数据库
- 等待上述完成
- 再次获取配方表以使用新配方更新反应组件状态
目前发生了什么:
- 配方被发布到数据库
- GET 配方在 Promise 从 POST 中返回。因此,组件状态得到 设置为旧数据。
我尝试使用 async/await,但这并没有什么不同。
这里是删减的代码:
API.js:
addRecipe: async function(newRecipe) {
let addRecipe = await axios.post('/api/recipes/new', newRecipe)
return addRecipe
},
getRecipes: function() {
return axios.get('/api/recipes');
}
Recipes.js:
import API from '../../utils/API';
state = {
dbRecipes: []
}
getRecipes = () => {
API.getRecipes()
.then(res => {
this.setState({
dbRecipes: res.data
})
})
}
handleFormSubmit = event => {
event.preventDefault();
API.addRecipe(formData).then(result => {
this.getRecipes()
})
}
添加配方控制器:
exports.addRecipe = function (req, res) {
const imgPath = req.file.path.replace('client/public','');
db.Recipe.create({
RecipeName: req.body.RecipeName,
RecipeDescription: req.body.RecipeDescription,
RecipeImage: imgPath
}).then(function (newRecipe) {
RecipeIngredients = JSON.parse(req.body.RecipeIngredients)
var promises = [];
for (var i = 0; i < RecipeIngredients.length; i++) {
var RecipeId = newRecipe.dataValues.id;
promises.push(
db.RecipeAmount.create({
Amount: RecipeIngredients[i].AmountForSmall,
Size: 'sm',
Type: 'smoothie',
IngredientId: RecipeIngredients[i].IngredientId,
RecipeId: RecipeId
})
);
promises.push(
db.RecipeAmount.create({
Amount: RecipeIngredients[i].AmountForMedium,
Size: 'md',
Type: 'smoothie',
IngredientId: RecipeIngredients[i].IngredientId,
RecipeId: RecipeId
})
);
promises.push(
db.RecipeAmount.create({
Amount: RecipeIngredients[i].AmountForLarge,
Size: 'lg',
Type: 'smoothie',
IngredientId: RecipeIngredients[i].IngredientId,
RecipeId: RecipeId
})
);
}
sequelize.Promise.all(promises).then(function () {
//this does get logged out in the backend console
console.log('DONE ADDING');
});
});
};
【问题讨论】:
-
您确定您的后端已正确实施,在 POST 请求返回响应之前,配方数据已插入您的数据库等?
-
@DacreDenny 据我所知,所有内容都已正确发布。所有记录都在数据库中,当我刷新页面时,状态也会正确更新。但是,既然你提出来了,我将为我的 addRecipe 控制器添加代码
-
您是否有任何其他类似的控制器可以按预期运行?看起来您的请求处理程序触发了一些异步函数并立即返回(即:请求将在异步函数完成之前完成)
-
@GeorgeChanturidze 请查看更新后的答案 - 这能解决您的问题吗?
-
你在哪里发送
addRecipe的回复?
标签: javascript reactjs promise async-await axios