【问题标题】:Make axios call from another axios promise and save returned data从另一个 axios 承诺进行 axios 调用并保存返回的数据
【发布时间】:2020-04-25 13:28:12
【问题描述】:

我正在从另一个axios调用的promise进行axios调用,代码如下所示,调用基本上是从第一种方法到第二种方法。

根据建议更新代码 它只是说:不能在异步函数之外使用关键字'await'然后我尝试了

var data = async () => {
        await this.checkParentLoggerLevel();
      };

还是不行

async updateLevel(logger, level, index) {
      alert(index);
      axios
        .post(
          'url'
        )
        .then(() => {
          var data = await this.checkParentLoggerLevel();

          alert('waiting');
          alert(
            'This will be executed before the second methods returns HEllo'
          );
          alert(data);
        });
    },

第二种方法:

async checkParentLoggerLevel() {
      alert('inside checkParentLoggerLevel ');
      return await axios
        .get('url')
        .then(() => {
          alert('returning hello');
          return 'hello';
        });
    },

我的目标是在第一种方法中将返回的hello 保存到数据变量中。这是行不通的。另一个问题是在this.checkParentLoggerLevel() 方法调用之后代码继续执行并且不等待返回的值。

【问题讨论】:

    标签: javascript ajax axios


    【解决方案1】:

    发生这种情况是因为在 checkParentLoggerLevel 内部,您没有等待 axios 承诺完成。你可以这样做:

    async checkParentLoggerLevel() {
      alert('inside checkParentLoggerLevel ');
      return await axios
        .get('url')
        .then((res) => {
          return 'hello';
        });
    }
    

    另外,您需要在 updateLevel 中等待,例如:

    async updateLevel() {
      axios
        .post(url)
        .then(async (res) => {
          var data = await this.checkParentLoggerLevel();
          alert("This will be executed before the second methods returns HEllo");
          alert(data);
        });
    }
    

    【讨论】:

    • return await 只有在 try-catch 块内时才有意义。如果不是,您可以删除awaitreturn await 工作,只是没有多大意义。
    • @Zuckerberg 当使用 var data = await this.checkParentLoggerLevel();它说不能在异步函数之外使用关键字'await'
    • 好的,然后尝试像async updateLevel() {那样使函数异步
    • await this.checkParentLoggerLevel() 现在不起作用,因为它所在的箭头函数(res) => { … } 没有标记为async。在修改之前它是正确的。
    【解决方案2】:

    你应该链接承诺,所以:

    updateLevel() {
      axios
        .post(url)
        .then(res => {
          return this.checkParentLoggerLevel.then(data => ([res, data]);
        })
        .then(([res, data]) => {
           // here
        });
    }
    

    或者简单地使用异步等待:

    async updateLevel() {
      const res = await axios.post(url);
      const data = await this.checkParentLoggerLevel();
      // Do whatever you want
    }
    

    【讨论】:

    • 当 const data = await this.checkParentLoggerLevel();;它说不能在异步函数之外使用关键字'await'
    • 您必须确保正如我在答案中所写,updateLevel 被标记为async
    猜你喜欢
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    • 2021-12-15
    • 2020-12-20
    • 2020-03-24
    • 2021-07-07
    相关资源
    最近更新 更多