我正在努力处理异步功能,尤其是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个标题,这是3个案例),我真的无法弄清楚原因。
以上代码基于How do I return the response from an asynchronous call?回答......
答案 0 :(得分:0)
通过评论的提示我得到了一个解决方案,基本上我使用我的“想要”返回值来设置状态,它必须这样做:
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
};