Browser: Internet Explorer 11
Platform: SharePoint 2016
I'm currently attempting to cache data into an array upon page load, with the intention of using these arrays efficiently throughout my code. I have four arrays that need to be populated with data from four different SharePoint lists. Using jQuery, I make calls to these lists to retrieve the necessary information. However, it seems that my current approach is flawed as the arrays are not being populated in time for me to use them. Here's a snippet of the code in question:
var cacheNavData = [];
var cacheSubNavData = [];
var cacheMegaMenuData = [];
var cacheCategoryMenuData = [];
$(document).ready(function(){
getNavData();
getSubNavData();
getMegaMenuData();
getCategoryMenuData();
})
function getNavData(){
// function body
}
function getSubNavData(){
// function body
}
function getMegaMenuData(){
// function body
}
function getCategoryMenuData(){
// function body
}
console.log(cacheNavData);
console.log(cacheSubNavData);
console.log(cacheMegaMenuData);
console.log(cacheCategoryMenuData);
It appears that my issue lies in the asynchronous nature of the calls, and I am still trying to grasp this concept fully. Despite reading various explanations and watching videos on the subject, I seem to struggle with finding a solution to this problem. When checking the console.log(), it's evident that the Ajax calls haven't returned the data yet. While I understand the root cause, I'm unsure how to rectify or prevent this delay. I attempted the following solution, but it proved unsuccessful. Any assistance would be greatly appreciated. Thank you!
// Updated code attempt
var cacheNavData = [];
var cacheSubNavData = [];
var cacheMegaMenuData = [];
var cacheCategoryMenuData = [];
$(document).ready(function() {
var cache1 = getData("Navigation", "cacheNavDataVar");
var cache2 = getData("Sub Navigation", "cacheSubNavDataVar");
var cache3 = getData("category menu", "cacheCategoryMenuDataVar");
var cache4 = getData("Mega Menu Category", "cacheMegaMenuDataVar");
$.when(cache1, cache2, cache3, cache4).done(function(results){
if(results){
createNavigation(cacheNavData)
}
})
});