繁体   English   中英

从另一个 axios promise 调用 axios 并保存返回的数据

[英]Make axios call from another axios promise and save returned data

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

基于建议的更新代码它只是说:不能在异步function之外使用关键字'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()方法调用代码执行继续并且不等待返回的值之后。

发生这种情况是因为在checkParentLoggerLevel中您没有等待axios promise 完成。 你可以这样做:

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

你应该链接承诺,所以:

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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM