简体   繁体   English

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

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

I am making an axios call from promise of another axios call, the code looks like below, the call is basically from the first method to the second method.我正在从另一个axios调用的 promise 进行 axios 调用,代码如下所示,调用基本上是从第一种方法到第二种方法。

UPDATED CODE BASED ON SUGGESTION It simply says: Can not use keyword 'await' outside an async function then I tried基于建议的更新代码它只是说:不能在异步function之外使用关键字'await'然后我尝试了

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

still did not work仍然没有工作

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

Second method:第二种方法:

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

My aim to to save the returned hello to data variable in first method.This is not working.我的目标是在第一种方法中将返回的hello保存到数据变量中。这是行不通的。 The other problem is after the this.checkParentLoggerLevel() methods call code execution continues and does not wait for the retuned value.另一个问题是在this.checkParentLoggerLevel()方法调用代码执行继续并且不等待返回的值之后。

This happens because inside checkParentLoggerLevel you are not waiting for the axios promise to complete.发生这种情况是因为在checkParentLoggerLevel中您没有等待axios promise 完成。 You can do it like:你可以这样做:

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

Also, you need to await inside updateLevel like:此外,您需要在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);
    });
}

You should chain the promises, so:你应该链接承诺,所以:

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

Or simply with async await:或者简单地使用异步等待:

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