I am creating one javascript library. In that I am using deferred methods for asynchronous call.
But the thing is, if I log the output json object is not showing all the items. But if I expand the object then it is showing actual values. Look the below screenshot.
In this console.log
showing that subFolders object initially contains 0 elements, but if I expand the object then subFolders containing two elements. This output object is coming from multiple asynchronous calls. Following is my code
RESTQueries.getFilesFromFolders = function(){
var execute = function(libraryName){
var libraryItems={rootFolder:[],subFolders:[]};
var deferred = $.Deferred();
var _url = makeProperUrl();
var itemsInRootFolder = getItemsFromFolder(libraryName,'files');
itemsInRootFolder.then(function(data){
var tempArray = [];
if(typeof(data.d.results)!='undefined' && data.d.results.length>0)
{
for(var i =0;i<data.d.results.length;i++)
{
tempArray.push({"name":data.d.results[i].Name});
}
}
libraryItems.rootFolder.push(tempArray);
}).then(function(){
var subFolders = getItemsFromFolder(libraryName,'folders');
subFolders.then(function(data){
for(var item in data.d.results){
var fName = data.d.results[item].Name;
if(fName!='Forms')
{
var subFolderItems = getItemsFromFolder(libraryName+"/"+fName ,'files');
subFolderItems.then(function(subItems,link){
var actualFolderName = link.split("/")[1];
var tempArray={};
var tempArray2 = [];
for(var i=0;i<subItems.d.results.length;i++){
tempArray2.push({"name":subItems.d.results[i].Name});
}
tempArray[actualFolderName]=tempArray2;
tempArray2="";
libraryItems.subFolders.push(tempArray);
});
}
}
});
}).then(function(){
deferred.resolve(libraryItems);
});
return deferred;
};
return{
execute:execute
}
}();
I am executing this function like,
RESTQueries.getFilesFromFolders.execute('HelpDocuments').then(function(data){
console.log(data);
},
function(err){
console.log(err);
});
Why json object is behaving like this? Where I am doing mistake?