gpt4 book ai didi

javascript - Axios POST promise 无法按预期工作

转载 作者:行者123 更新时间:2023-11-30 20:17:13 27 4
gpt4 key购买 nike

我有一个带有 Sequelize/mysql 的 react/node/express 应用程序。使用 Axios 进行 API 调用。

我需要做的:

  1. 将食谱发布到数据库
  2. 等待以上完成
  3. 再次获取配方表以使用新配方更新 react 组件状态

目前发生的事情:

  1. 食谱发布到数据库
  2. 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()
})
}

添加配方 Controller :

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

});
};

最佳答案

我认为解决方案是通过确保调用 res 回调来调整您的 addRecipe Controller 。看到您的“完成添加”消息已记录,我们可以调用 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 post 只有在新数据进入数据库后才会完成。反过来,这应该导致对 API.getRecipes() 的调用仅在数据库更新后才被调用——然后一切都应该按预期工作

关于javascript - Axios POST promise 无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51813853/

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