gpt4 book ai didi

javascript - Axios 返回未决 promise

转载 作者:行者123 更新时间:2023-12-05 08:25:53 25 4
gpt4 key购买 nike

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

最佳答案

首先如果。如果您使用默认的 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;
}
}

关于javascript - Axios 返回未决 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60740335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com