Axios 返回未决的承诺

Kev*_*n.a 2 javascript promise async-await axios

我希望这个函数返回 true 或 false,而不是我得到

/**
 * Sends request to the backend to check if jwt is valid
 * @returns {boolean} 
 */
const isAuthenticated = () => {
    const token = localStorage.getItem('jwt'); 
    if(!token) return false; 
    const config = {headers : {'x-auth-token' : token}}; 

    const response = axios.get('http://localhost:8000/user' , config)
    .then(res =>  res.status === 200 ? true : false)
    .catch(err => false);

    return  response;
}   

export default isAuthenticated; 
Run Code Online (Sandbox Code Playgroud)

我尝试将它们分开并使用 async/await :

const isAuthenticated = async () => {
    const response = await makeRequest();
    return  response;
}   


const makeRequest = async () => { 
    const token = localStorage.getItem('jwt'); 
    const config = {headers : {'x-auth-token' : token}}; 
    const response = await axios.get('http://localhost:8000/user' , config)
    .then(res =>  res.status === 200 ? true : false)
    .catch(err => false);

    return response;
}
Run Code Online (Sandbox Code Playgroud)

而且还是一样。。

经过一些建议:

const isAuthenticated =  () => {
    const response =  makeRequest();
    return  response;
}   


const makeRequest = async () => { 
    try {
        const token = localStorage.getItem('jwt'); 
        const config = {headers : {'x-auth-token' : token}}; 
        const response = await axios.get('http://localhost:8000/user', config);
        if (response.status === 200) { // response - object, eg { status: 200, message: 'OK' }
            console.log('success stuff');
            return true;
        }
        return false;
   } catch (err) {
        console.error(err)
        return false;
   }
}
export default isAuthenticated; 
Run Code Online (Sandbox Code Playgroud)

Ale*_*lex 9

首先如果。如果您使用默认的承诺 then & catch,那么成功操作应该在 'then' 函数中处理。

axios.get('http://localhost:8000/user', config)
.then(res => console.log('succesfull stuff to be done here')
.catch(err => console.error(err)); // promise
Run Code Online (Sandbox Code Playgroud)

如果你想使用 async/await 语法糖,我个人喜欢它

const makeRequest = async () => { 
    try {
    const token = localStorage.getItem('jwt'); 
    const config = {headers : {'x-auth-token' : token}}; 
    const response = await axios.get('http://localhost:8000/user', config);
    if (response.status === 200) { // response - object, eg { status: 200, message: 'OK' }
      console.log('success stuff');
     return true;
    }
    return false;
   } catch (err) {
     console.error(err)
     return false;
   }
}
Run Code Online (Sandbox Code Playgroud)