I'm trying to make a function that returns a string containing a jwt token, the function used in Amplify returns a promise and I can't get my head around promises but after some struggling, I've managed to get my function to get the string I need from the promise and print it to the console but when I then return this string from the function so I can call it from various places the resulting data is now a promise again. No idea what I'm doing wrong.
async function getToken() {
let userData = await Auth.currentAuthenticatedUser().then(result => result.signInUserSession).then(result => result.accessToken).then(result => result.jwtToken);
console.log(userData); // this prints the token perfectly as text to the console
return(userData); // I want this to return the token as a string not a promise
}
console.log(getToken(); // this prints a promise to the console again even though I've got it to a string in the function.
Think I've sussed it now thanks to @tfarmer4 and @Arish Khan. In my head I wanted to get the token as a string variable so I could pass it into my API call functions but I realise now I will need to call it from within each function so below is my example solution.
function getToken() {
return Auth.currentAuthenticatedUser().then(result => result.signInUserSession).then(result => result.accessToken).then(result => result.jwtToken);
}
function callAPI () {
getToken().then(data => {
let token = data;
console.log(token);
//more lines here such as calling my API using token as the variable of the jwt token
}
);
};