I am trying to get an auth token from an API and then store that Auth token and use it in subsequent calls to the API.
This is the code to get the token
const getToken = async (): Promise<string | void> => {
const response = await fetch('https://exampleapi.com/auth', {
method: 'POST',
body: JSON.stringify(body),
headers: headers,
agent: httpsAgent
})
const data = await response.text().then(txt => {
const cred = xml2json(txt);
const cred2: authResponse = JSON.parse(cred);
const tkn = cred2.elements[0].elements[0].attributes.token;
return tkn;
}).catch(err => console.log(err));
return data;
}
However it is returning a promise even though I am .then() and .catch() -ing.
If I put a console.log() within the .then(), I am able to see the token that I want. However I'm not able to return it as a value so that it can be stored.
const tkn = getToken().then(data => console.log(data)).catch(err => console.log(err));
I want the value of the token to be returned, not just to be able to console.log() the value I'm looking for. All the examples I am seeing are simply showing that I can console.log() the value I am looking for within the .then(), however that is not what I am trying to do. Sorry if this is not worded correctly would be happy to update with any relevant information needed. Would like to avoid top level await if possible.