Axios POST承诺无法按预期运行

时间:2018-08-13 00:12:06

标签: javascript reactjs promise async-await axios

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

我需要做什么:

  1. 将配方发布到数据库
  2. 等待以上内容完成
  3. 再次获取配方表,以使用新配方更新反应成分状态

当前发生的情况:

  1. 食谱已发布到数据库
  2. GET配方在执行之前 承诺从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()
    })
  }

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

  });
};

1 个答案:

答案 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()的调用仅在数据库更新后才被调用-然后一切都将按预期工作