2017-09-05 50 views
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?答案...

+0

的[?我如何返回從一個異步調用的響應(可能的複製https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from異步調用) –

+1

值將在回調方法'codRes'中可用,執行'function codRes(c){console.log('c',c)cod = c; };'它會打印正確的值,但是checkCod不會返回值。 –

+1

你說這是基於*如何返回來自異步調用的響應*,但這告訴我你不瞭解異步函數的問題以及如何處理它們。你只是不能從異步回調中返回,你必須在回調中處理結果和依賴它的任何**。 –

回答

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