我有一个带有Sequelize / mysql的react / node / express应用程序。使用Axios进行API调用。
我需要做什么:
当前发生的情况:
我尝试使用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()
})
}
addRecipe控制器:
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');
});
});
};
答案 0 :(得分:1)
我认为解决方案是通过确保调用res
来调整您的addRecipe控制器。看到您的“ DONE ADDING”消息已记录,我们可以按以下方式调用res
回调:
sequelize.Promise.all(promises).then(function () {
//this does get logged out in the backend console
console.log('DONE ADDING');
res.send(); // <-- call the response callback to send a response back
// to client only after DB has been updated
});
这应该确保仅当新数据位于数据库中时,您才能在客户端进行axio发布。反过来,这应该导致对API.getRecipes()
的调用仅在数据库更新后才被调用-然后一切都将按预期工作