簡體   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