【问题标题】:Not getting returned value from async await function没有从异步等待函数中获取返回值
【发布时间】:2021-01-25 21:37:37
【问题描述】:

当我按下按钮时,我得到未定义的返回值。

<Button btnType="outline" onClick={LockUnlockAccountHandler}>
     lock client’s account
</Button>

const LockUnlockAccountHandler = async () => {
  const status = await LockUnlockAccount(detailData?.userId, detailData?.blocked ? 'UNLOCK' : 'LOCK');
  console.log(status)
  if(status){
    setDetailData({
      ...detailData,
      blocked: !detailData.blocked
    })
  }
}

状态值在上面的函数中是未定义的,从下面的函数中应该是真或假。

export async function LockUnlockAccount(clientID, dataVal) {
  
  var config = {
    method: 'post',
    url: endpoint.lockAccount + clientID + "/status"  + endpoint.key,
    headers: { 
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    data : qs.stringify({
      'status': dataVal 
    })
  };
  axios(config)
    .then(function (response) {
      //console.log(JSON.stringify(response));
      if (response.status === 200) {
        toast('succès');
        return true;
      }
      return false;
    })
    .catch(function (error) {
      console.log(error);
      toast('error');
      return false;
    });
}

【问题讨论】:

  • axios(config) -> return axios(config) 或只是 await 结果并从函数本身返回。您已将该函数标记为异步,但不要在其中的任何位置使用 await

标签: javascript reactjs asynchronous async-await


【解决方案1】:

你没有从LockUnlockAccount返回任何东西

你需要做的

return axios(config).then(...)

【讨论】:

    【解决方案2】:

    您必须从 axios 返回响应,这是包装函数将返回的内容。只需在 axios 调用前添加 return。
    以下是您的更新代码

    export async function LockUnlockAccount(clientID, dataVal) {
      
      var config = {
        method: 'post',
        url: endpoint.lockAccount + clientID + "/status"  + endpoint.key,
        headers: { 
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        data : qs.stringify({
          'status': dataVal 
        })
      };
      return axios(config)
        .then(function (response) {
          //console.log(JSON.stringify(response));
          if (response.status === 200) {
            toast('succès');
            return true;
          }
          return false;
        })
        .catch(function (error) {
          console.log(error);
          toast('error');
          return false;
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-30
      • 2020-12-23
      • 1970-01-01
      • 2018-01-03
      • 1970-01-01
      • 2020-03-13
      • 2011-03-04
      • 2022-07-06
      • 2020-08-19
      相关资源
      最近更新 更多