Axios返回待定承诺

brtdzjyr  于 2023-02-15  发布在  iOS
关注(0)|答案(2)|浏览(129)

我希望这个函数返回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;
rekjcdws

rekjcdws1#

首先,如果使用默认的promise 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

如果你想使用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;
   }
}
lymnna71

lymnna712#

您必须使用async/await,如下所示:

const isAuthenticated =async () => {
const token = localStorage.getItem('jwt'); 
if(!token) return false; 
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;

}

相关问题