I am using the Github API to retrieve data about one of my repos and I am running into trouble with callback functions and recursive functions overlapping (as in recursive functions with callbacks attached to them)
Here is the script on jsfiddle as well as below:
(function () {
'use strict';
function makeAJAXCall(hash, cb) {
$.ajaxSetup({
accept: 'application/vnd.github.raw',
dataType: 'jsonp'
});
$.ajax({
url: hash,
success: function (json) {
//console.info(json);
// Time for callback to be executed
if (cb) {
cb(json);
}
},
error: function (error) {
console.error(error);
// an error happened, check it out.
throw error;
}
});
}
function parseBlob(hash) {
return makeAJAXCall(hash, function (returnedJSON) { // no loop as only one entry
console.log(returnedJSON.data);
return returnedJSON.data.content;
});
}
function walkTree(hash) {
var tree = 'https://api.github.com/repos/myusername/SVG-Shapes/git/trees/' + hash;
return makeAJAXCall(tree, function (objectedJSON) {
var objectList = [], i, entry;
for (i = 0; i < objectedJSON.data.tree.length; i += 1) {
entry = objectedJSON.data.tree[i];
//console.debug(entry);
if (entry.type === 'blob') {
if (entry.path.slice(-4) === '.svg') { // we only want the svg images not the ignore file and README etc
//console.info(entry.path)
objectList.push(parseBlob(entry.url));
}
} else if (entry.type === 'tree') {
objectList.push(walkTree(entry.sha));
}
}
if (cb) {
console.log(objectList);
cb(objectList);
}
return objectList;
});
}
$(document).ready(function () {
var returnedObjects = walkTree('master', function (objects) { // master to start at the top and work our way down
console.info(objects);
});
});
}());
The JSON returned is either blog (file) or tree (directory). If it is a tree the walkTree function is called again. I do not understand how the callback will behave here as well as how to get the data it (should) return(s) out of the function and into the final block at the very bottom.
Can someone clarify how I should be doing this?