代码之家  ›  专栏  ›  技术社区  ›  geochanto

AXIOS POST承诺不按预期工作

  •  1
  • geochanto  · 技术社区  · 8 年前

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

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

    1. 配方被发布到数据库
    2. 获取配方在 诺言从岗位上收回。因此,组件状态得到 设置为旧数据。

    以下是简略代码:

    addRecipe: async function(newRecipe) {
        let addRecipe = await axios.post('/api/recipes/new', newRecipe) 
        return addRecipe
    },
    getRecipes: function() {
        return axios.get('/api/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');
        });
    
      });
    };
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Dacre Denny    8 年前

    我认为解决方案是通过确保 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只在新数据在DB之后完成。反过来,这会导致 API.getRecipes()