Axios返回承诺待定

时间:2020-03-18 13:11:40

标签: 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; 

我尝试将它们分离并使用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;
}

仍然一样。.

经过一些建议:

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; 

1 个答案:

答案 0 :(得分:3)

首先,如果。 如果您使用的是默认承诺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

如果您想使用异步/等待语法糖,我个人喜欢它

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