I have an async function that generates a new token if a user's token expires. I copied and pasted the async function code into this project and the class and constructor were already built.
I want to call the async function but I'm not sure how/where to do it, especially with the constructor function present. I can see how and where the other async functions are called (i.e. var _token = await sessionGet(_tokenName)
), but since the async function I want to call is the outermost async function (if that makes sense) I'm not sure where I'd call it.
Here's what I know (correct me if I'm wrong):
I can't use
await
outside an async functionIt's a bad practice to have a
constructor function
return aPromise
My async function has to be async or else it'll "break the flow" of the rest of the code---
async
is used multiple times throughout
export default class {
constructor() {
this.setTokenVar();
// other function calls
}
setTokenVar() {
async function permissionToCallAPI() { // -------- this is what I want to call
const _tokenName = "tokenSet",
_RestHost = "https://.../.../api";
async function sessionGet(key) {
let stringValue = window.sessionStorage.getItem(key);
if (stringValue != null) {
try {
const {
value,
expirationDateStr
} = JSON.parse(stringValue);
if (value && expirationDateStr) {
let expirationDate = new Date(expirationDateStr);
if (expirationDate <= new Date()) {
throw "Expired Token";
}
const isValid = await isAuthorized(value.value);
if (isValid) {
console.log("Valid Token");
return value;
} else {
throw "Expired Token";
}
} // if (value && expirDateStr)
} catch (e) {
console.log(e);
window.sessionStorage.removeItem(key);
}
}
return null;
}
async function isAuthorized(key) {
let ret = false;
await axios.post(_RestHost + "/User/GenerateToken", null, {
withCredentials: true,
async: false,
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json",
"Authorization": key
}
}).then(resp => {
ret = true;
})
.catch(err => {
console.log("Failed Authentication.");
});
return ret;
}
// add into session
function sessionSet(key, value, expirationInMin) {
if (!expirationInMin) {
expirationInMin = 59;
}
var expirationDate = new Date(
new Date().getTime() + 60000 * expirationInMin
);
var newValue = {
value: value,
expirationDateStr: expirationDate.toISOString()
};
window.sessionStorage.setItem(key, JSON.stringify(newValue));
}
var _token = await sessionGet(_tokenName);
if (_token == null) {
let request = axios
.get(_RestHost + "/User/GenerateToken", {
withCredentials: true
});
return request
.then(response => {
const authToken = response.data.AuthToken;
sessionSet(_tokenName, authToken);
return authToken;
})
.catch(err => {
throw err;
});
} else {
return _token;
}
} // permToCallAPI
} // setTokenVar()
}