0

Please excuse any lack of industry terminology. Still learning here!

I'm writing a script that pushes analytics data from a platform to excel with the intentions of scheduling the script to run via PowerAutomate several times a day. The platform's api is fairly simple, but I've hit a wall straight out the gate. After the initial call to obtain the session token, I can't think of a workaround for defining it for retrieval later. When I define sessionToken as xhr.responseText, it returns as undefined when referenced. To my understanding, you can't define a global variable from within a function, but how is the session token supposed to be included in subsequent calls without a defined reference?

const appID = 'Application ID';
const tenantID = 'Tenant ID';
var sessionToken;
const getApiToken = () => {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "API URL with appended Application ID", true);
    xhr.onload = function (e) {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                console.log(xhr.responseText);
                const sessionToken = xhr.responseText;
            } else {
                console.error(xhr.statusText);
            }
        }
    }
    xhr.onerror = function (e) {
        console.error(xhr.statusText);
        console.error(e);
    }
    xhr.send("")
}
console.log(sessionToken); //Test-Should return same output as getApiToken()
getApiToken();

  • Apart from the issue with asynchrony, you are literally logging the token *before* calling the function that fetches it. – Bergi Jan 18 '21 at 18:40
  • "*how is the session token supposed to be included in subsequent calls*" - you need to learn promises or at least callbacks to make subsequent asynchronous calls. – Bergi Jan 18 '21 at 18:42

0 Answers0