0

I need to access the token so I can utilize it in other places in my application. There is a scope issue I am running into, and I have set a variable outside of the function (I have seen that in other use cases it works, if you return to it.)

let myToken;
const getToken = async function () {
  try {
    const fetchToken = await fetch(
      'https://api.website.com/v1/authenticate',
      {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email: 'username123',
          password: 'password123',
        }),
      }
    );
    const tokenData = await fetchToken.json();
    return (myToken = tokenData.data.token);
  } catch (err) {
    console.error(err);
  }
};

getToken();
console.log(myToken);

Undefined is returned.

Thanks for taking a look.

dkohn1337
  • 3
  • 3
  • `console.log(myToken);` - this statement will execute before `myToken` is initialzed inside the async function. That's why you get undefined. To access `myToken`, you wither need to await the call to `getToken` function or chain `.then()` method call. – Yousaf Feb 07 '21 at 09:47
  • getToken().then(token => console.log(myToken)); this still does not save it as a global object. – dkohn1337 Feb 07 '21 at 10:08
  • You can't do what you are trying to do. You can use `myToken` only _after_ it has been initialized. – Yousaf Feb 07 '21 at 10:16

0 Answers0