I am running this block of asynchronous code on the first page that loads on my site (index page) and setting the resulting data in a global variable for use on other pages of the site. The problem is, on other pages of the site when I try to access the data returned and stored in the global variable, I can't do anything with the data until it is fully loaded, so I get errors that say the data is 'undefined'. What I need is a way to make sure the asynch code is completed and the data is available so that it can be used without error.
var apiInitData = new Object();
// This block is asynchronous and sets the data in apiInitData
bn.push(["init", function() {
bn.apiId.init({
loginSuccess: function (event){
var params = {cross_app: true};
bn.api.callApi("/access/list", params, function(data) {
apiInitData.data = data.data;
});
}
});
}]);
In other pages that load after the index page, I try to access this global variable:
console.log("apiInitData: ", apiInitData);
This does return the data in apiInitData. I can view the object in my console.
However, if I try to print the length of that data on the next line:
console.log("length", apiInitData.data.length);
I get an error:
Uncaught TypeError: Cannot read property 'length' of undefined
I know this is due to the apiInitData variable waiting for the asynch code to complete, but I don't know what I can do to wait for it. I have read about callback functions, but the more I read, the more confused I get and am just not seeing what needs to be done here.
How can I use the data in apiInitData on other pages of the site only after the data is completely fetched by the asynch code block?