I have been studying and trying to understand Asynchronous javascript. After much reading and a suggestion to use the bluebird library because I'm using IE11, I tried it on a simple example I created but it isn't working as expected. I added a settimeout in each function to simulate asynchronicity. The goal is to populate the arrays so I can console.log() the array values but it was to no avail. In my promise.all
, I call createNavigation() which suggests that all my arrays are populated but it isn't. Also, numbers are being returned for the results in promise.all
.
What am I doing wrong or misunderstanding? Why are my arrays being logged to the console as blanks?
var cacheNavData = [];
var cacheSubNavData = [];
var cacheMegaMenuData = [];
var cacheCategoryMenuData = [];
getNavData();
getSubNavData();
getMegaMenuData();
getCategoryMenuData();
var promises = [
getNavData(),getSubNavData(),getMegaMenuData(),getCategoryMenuData()
]
Promise.all(promises)
.then(function(results){
console.log(results)
createNavigation()
})
function getNavData(){
return setTimeout(function(){
cacheNavData[0] = "Soup";
cacheNavData[1] = "Sandwich";
cacheNavData[2] = "Rice";
}, 3000);
}
function getSubNavData(){
return setTimeout(function(){
cacheSubNavData[0] = "Apple";
cacheSubNavData[1] = "Beans";
cacheSubNavData[2] = "Carrot";
}, 3000);
}
function getMegaMenuData(){
return setTimeout(function(){
cacheMegaMenuData[0] = "Donkey";
cacheMegaMenuData[1] = "Eagle";
cacheMegaMenuData[2] = "Frog";
}, 3000);
}
function getCategoryMenuData(){
return setTimeout(function(){
cacheCategoryMenuData[0] = "Grapes";
cacheCategoryMenuData[1] = "Hand";
cacheCategoryMenuData[2] = "Igloo";
}, 3000);
}
function createNavigation(){
console.log("All arrays have been populated. Let's build the navigation.")
}
console.log(cacheNavData);
console.log(cacheSubNavData);
console.log(cacheMegaMenuData);
console.log(cacheCategoryMenuData);