2017-09-05 78 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 
};