【问题标题】:Axios update value outside of then to break the loopAxios 在 then 之外更新值以打破循环
【发布时间】:2021-01-06 20:09:22
【问题描述】:

我目前仍在学习使用 React Native。

我想要做的是将限制值更新为 1,这样它会破坏 while 循环,但我不确定如何执行它,因为我无法从 .then() 内部更新值在 Axios POST 调用中。 很高兴有人能指出任何处理此问题的方法。感谢您的帮助。

var limit = 0;
        while (limit == 0) {
          running = running + 20;
          console.log("restart");
          postDataCalories = {
            "query": `${running} minutes run and ${walking} minutes walking`,
            "gender":"male",
            // "nf_calories": 363.62,
            "weight_kg":63.5,
            "height_cm":167.64,
            "age":30
          };
          console.log(`${running} minutes run and ${walking} minutes walking`);
          axios.post('https://trackapi.nutritionix.com/v2/natural/exercise', postDataCalories, axiosConfig2)
          .then((res3) => {
            console.log("exercise RESPONSE RECEIVED: ", res3);
            let caloriesFood = res2.data.foods[0].nf_calories;
            let caloriesExercise = res3.data.exercises[0].nf_calories;
            let caloriesDifferences = caloriesFood - caloriesExercise;
            console.log("hi " + caloriesDifferences);
            if (caloriesDifferences < 50){
              console.log('done');
              limit = 1;
            } else {
              console.log('nope');
            }
          })
        }

【问题讨论】:

    标签: react-native axios


    【解决方案1】:

    在您的情况下,您不能中断 then 函数内的 while 循环,因为该函数是在不同的时间调用的(他们称之为异步)。

    您可以做两件事。如果您可以在您的环境中访问 await/async,您可以将其重写为:

    async someFunction() { 
            var limit = 0;
            var running = 1;  // arbitrarily start at 1.
            while (limit == 0) {
              running = running + 20;
              console.log("restart running " + running);
              postDataCalories = {
                "query": `${running} minutes run and ${walking} minutes walking`,
                "gender":"male",
                // "nf_calories": 363.62,
                "weight_kg":63.5,
                "height_cm":167.64,
                "age":30
              };
              console.log(`${running} minutes run and ${walking} minutes walking`);
              var res3 = await axios.post('https://trackapi.nutritionix.com/v2/natural/exercise', postDataCalories, axiosConfig2)
    
                console.log("exercise RESPONSE RECEIVED: ", res3);
                let caloriesFood = res2.data.foods[0].nf_calories;
                let caloriesExercise = res3.data.exercises[0].nf_calories;
                let caloriesDifferences = caloriesFood - caloriesExercise;
                console.log("hi " + caloriesDifferences);
                if (caloriesDifferences < 50){
                  console.log('done');
                  limit = 1;
                  // you may also do:
                  break;
                } else {
                  console.log('nope');
                }
              }
            }
    }
    

    对于通常的网络条件,它需要现代浏览器 (Firefox/Chrome)(或者当你有 babel / regenerator-runtime 时可能会成功,也许你的设置已经能够编译/运行它。)

    如果您无权访问 async/await,那么您需要应用递归(以解决同步问题)。通常您可以按顺序执行任务(连续、逐步、使用 while 循环),现在您可以编写如下内容:

    function runTheLoop(running, walking) {
              postDataCalories = {
                "query": `${running} minutes run and ${walking} minutes walking`,
                "gender":"male",
                // "nf_calories": 363.62,
                "weight_kg":63.5,
                "height_cm":167.64,
                "age":30
              };
              console.log(`${running} minutes run and ${walking} minutes walking`);
              axios.post('https://trackapi.nutritionix.com/v2/natural/exercise', postDataCalories, axiosConfig2)
              .then((res3) => {
                console.log("exercise RESPONSE RECEIVED: ", res3);
                let caloriesFood = res2.data.foods[0].nf_calories;
                let caloriesExercise = res3.data.exercises[0].nf_calories;
                let caloriesDifferences = caloriesFood - caloriesExercise;
                console.log("hi " + caloriesDifferences);
                if (caloriesDifferences < 50){
                  console.log('done');
                  // limit = 1;
                  return;
                } else {
                  console.log('nope');
     
                  // This is the recursive variant of "running the loop again"
                  return runTheLoop(running + 20, walking + 20);
                }
              })
            }
        }
    
    
    // Somewhere:
    console.log("restart");
    // one minute of walking and one minute of running.
    runTheLoop(1, 1);
    
    

    注意:我已经使用您的代码来制作与您的情况相关的示例,我无法自己测试它,因此如果您复制并粘贴它可能无法直接工作。

    【讨论】:

    • 您好!感谢您与我分享您的解决方法,先生。我确实尝试了异步等待替代方法,但似乎限制仍然不会破坏循环并且它会一直持续下去。我有一个问题,我可以在“if (caloriesDifferences
    • 如果它继续按顺序进行(一个接一个),那么我们就非常接近了!是的,您可以更改运行变量,但我怀疑在每个循环上运行应该增加 20,如果不是这种情况,那么我们可能做错了什么。您可以做的另一件事是除了通过 limit = 1 中断之外,您还可以使用“break;”陈述。我将更新代码示例以显示它。
    • 实际上,我确实通过弄乱 async/await 方法使它工作。先生,非常感谢您对什么和这个有效的详细解释! @JoshuaAngnoe
    猜你喜欢
    • 2021-05-02
    • 2013-03-20
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 2019-10-11
    • 1970-01-01
    • 2011-08-18
    • 2021-12-20
    相关资源
    最近更新 更多