我正在努力处理异步函数,尤其是 Axios。
我有一个函数,它向 WS 传递两个值(重要的是“cod”),并且基于 http 响应必须返回 cod 或“”。
function checkCod(callback){
axiosCall.get('codecheck.php',{params:{user:usr,cod:cod}})
.then((response)=>{
if(response.status!==200){//if I give an error http response callback argument is ""
console.log("false code");
callback("");
}else{
callback(cod); //if everything goes right callback argument is cod (passed as the WS)
}
})
.catch((error)=>{
console.log(error);
callback(""); //if I give an error http response callback argument is ""
});
}
function codRes(c){
cod=c;
return cod;
};
return checkCod(codRes);
永远不会返回值(有 200 或 500 或 400 个 header ,这是 3 种情况),我真的不明白为什么。
以上代码基于How do I return the response from an asynchronous call?回答...
最佳答案
根据评论的提示,我得到了一个解决方案,基本上我是使用我的“wannabe”返回值来设置状态,必须这样做:
function checkCod(callback){
axiosCall.get('codecheck.php',{params:{user:usr,cod:cod}})
.then((response)=>{
if(response.status!==200){//if I give an error http response callback argument is ""
console.log("false code");
callback("");
}else{
callback(cod); //if everything goes right callback argument is cod (passed as the WS)
}
})
.catch((error)=>{
console.log(error);
callback(""); //if I give an error http response callback argument is ""
});
}
function codRes(c){
this.setState({
cod:c
})
//or everything I might wanna do with my c variable resulting from async function
};
关于javascript - 无法通过回调返回异步值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46053037/