繁体   English   中英

未从异步等待 function 获取返回值

[英]Not getting returned value from async await function

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

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

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

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

您没有从LockUnlockAccount返回任何内容

你需要做

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

您必须从 axios 返回响应,这将由包装 function 返回。 只需在 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;
    });
}

暂无
暂无

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

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