Q:

Uncaught ReferenceError: variableis not defined

I have a button on a website which executes the below function getAccountsToPanel when clicked. The function calls the available Google Tagmanager accounts of the logged in user and places them into a panel. The function is part of the external javascript file gtm_api_handling.js
var accounts;
var accountClicks = 0;
var accountButtons ="";
function getAccountsToPanel() {
   if (accountClicks == 0) {
     var request = gapi.client.request({"method":"GET", ath":"tagmanager/v2/accounts"});
     request.then(function(response){accounts = response.result.account});
     accounts.forEach(function(elem){accountButtons += `<button class="accordion">Account: ${JSON.stringify(elem.name)}</button>`;})
     var x = document.getElementById("accountPanel");
     x.innerHTML = accountButtons;
     accountClicks = 1; // make sure this function is not doing anything again after its first execution
   }
}

However, on the first click of this button, I get the error message:
gtm_api_handling.js:147 Uncaught TypeError: Cannot read property 'forEach' of undefined
    at getAccountsToPanel (gtm_api_handling.js:147) // this is line that begins with accounts.forEach in the above function
    at HTMLButtonElement.onclick (page2.html:52) // this is the buttons position on the main html sheet

If I then either go to the console and see the contents of "accounts" or click on the button again (rerun the function), everything behaves like I would expect it to. 
Has anyone seen this before? Do you have an idea how to fix this?

A:

Referring to Google API Client Library, it seems like you need to put the forEach into the then callback function. Something like this might work:
var accounts;
var accountClicks = 0;
var accountButtons ="";
function getAccountsToPanel() {
   if (accountClicks == 0) {
     var request = gapi.client.request({"method":"GET", "ath":"tagmanager/v2/accounts"});
     request.then(function(response) {
         accounts = response.result.account;
         accounts.forEach(function(elem){accountButtons += `<button class="accordion">Account: ${JSON.stringify(elem.name)}</button>`;})
         var x = document.getElementById("accountPanel");
         x.innerHTML = accountButtons;
     });
     accountClicks = 1; // make sure this function is not doing anything again after its first execution
   }
}

