亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從另一個 axios 承諾進行 axios 調用并保存返回的數據

從另一個 axios 承諾進行 axios 調用并保存返回的數據

牛魔王的故事 2022-07-15 09:55:00
我正在從另一個調用的 promise 進行 axios 調用axios,代碼如下所示,調用基本上是從第一種方法到第二種方法?;诮ㄗh的更新代碼 它只是說:不能在異步函數之外使用關鍵字'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()方法調用代碼執行繼續并且不等待返回值之后。
查看完整描述

2 回答

?
斯蒂芬大帝

TA貢獻1827條經驗 獲得超8個贊

發生這種情況是因為你內心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);

    });

}


查看完整回答
反對 回復 2022-07-15
?
慕少森

TA貢獻2019條經驗 獲得超9個贊

你應該鏈接承諾,所以:


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

}


查看完整回答
反對 回復 2022-07-15
  • 2 回答
  • 0 關注
  • 304 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號