![](/img/trans.png)
[英]Having troubles getting returned value from an async/await function on ES6, how to solve it?
[英]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.