1
我正在努力處理異步函數,尤其是Axios。無法使用回調返回異步值
我得到一個函數,傳遞給WS兩個值(重要的是'鱈魚')和基於http響應必須返回鱈魚或「」。
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?答案...
的[?我如何返回從一個異步調用的響應(可能的複製https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from異步調用) –
值將在回調方法'codRes'中可用,執行'function codRes(c){console.log('c',c)cod = c; };'它會打印正確的值,但是checkCod不會返回值。 –
你說這是基於*如何返回來自異步調用的響應*,但這告訴我你不瞭解異步函數的問題以及如何處理它們。你只是不能從異步回調中返回,你必須在回調中處理結果和依賴它的任何**。 –