I am trying to make a function called isAuthenticated() that returns true or false depending on the authentication state obviously. When the user logs in, I get a token as a response that I store in local storage & use in authentication required requests using the Bearer authentication method. Now my code looks like this:
// axios instance
const a = axios.create({
baseURL: "http://mydomain/api",
withCredentials: false,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
});
const testToken= () => {
a.defaults.headers["Authorization"] = `Bearer ${localStorage.getItem(
"token"
)}`; // using bearer authintication
return a.get(`/isLogin`); // api route to check token state
};
// my function
function isAuthenticated() {
if (!localStorage.token) {
return false;
} else {
testToken()
.then((response) => {
return true;
})
.catch((error) => {
if (error.response.status === 401) {
return false;
}
});
}
}
console.log(isAuthenticated()); // this logs undefined
My problem is that it logs undefined. Now I understand that the reason for this is that the axios get method is a promise, & that the code continues execution before it resolves, so my question is: Is there a way to block code from executing until it resolves?
I think that there is something fundamentally wrong with my logic, so if you have a proper way of implementing this please help me.
When you return value from withing promise callback you return into a void. What you need is change how you call your isAuthenticated function:
// axios instance
const a = axios.create({
baseURL: "http://mydomain/api",
withCredentials: false,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
});
const testToken= () => {
a.defaults.headers["Authorization"] = `Bearer ${localStorage.getItem(
"token"
)}`; // using bearer authintication
return a.get(`/isLogin`); // api route to check token state
};
// my function
function isAuthenticated() {
return new Promise((resolve, reject) =>
{
if (!localStorage.token) {
resolve(false);
} else {
testToken()
.then((response) => {
resolve(true);
})
.catch((error) => {
if (error.response.status === 401) {
resolve(false);
}
});
}
});
}
isAuthenticated().then((response) =>
{
if (result)
{
//authenticated
}
else
{
//not authenticated
}
});
You could use await to make it less "cumbersome", but still you'll need re-evaluate how you call async functions.
function isAuthenticated(isReject) {
return new Promise((resolve, reject) =>
{
setTimeout(() => isReject ? reject("hello word rejected") : resolve("hello world"), 3000); //delay 3sec
});
}
async function myFunc(id)
{
const result = await isAuthenticated(id == 3); //wait until promise is resolved
console.log("result" + id, result);
return "this was sent to 'then' callback: " + result;
};
console.log("myFunc return", myFunc(1));
console.log("myFunc return2", myFunc(2)
.then((result) => console.log("result2 within then:", result)) //this will not fire
.catch((result) => console.log("rejected2:", result)));
console.log("myFunc return3", myFunc(3)
.then((result) => console.log("result3 within then:", result)) //this will not fire
.catch((result) => console.log("rejected3:", result)));