I have make some functions to retrieve data using the Github API. I have the callbacks in place to get the data but I am sure how to understand where a function exits and when I stops modifying things.
For example in the code below, in the first function, when the AJAX call is successful, the callback is executed in the second function where the data is manipulated. Does that mean the the return in the first function is not needed or used? And in the second function is the data used and pushed to the array and then the array returned or is it the other way around where the (empty) array is returned and then the callback does its thing.
I am ultimately trying to get the data from the callback into an object and return that filled object from the parent function.
function makeAJAXCall(hash, cb) {
var returnedJSON, cb = cb, hash = hash;
$.ajax({
accepts: 'application/vnd.github-blob.raw',
dataType: 'jsonp',
url: hash,
success: function (json) {
console.info(json);
returnedJSON = 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;
}
});
return returnedJSON;
}
function parseBlob(hash) {
var objectedJSON, objectList = [], i;
objectedJSON = makeAJAXCall(hash, function (objectedJSON) { // no loop as only one entry
objectList.push(objectedJSON.content);
});
return objectList;
}
function walkTree(hash) {
var objectedJSON, objectList = [], i, entry;
var hash = 'https://api.github.com/repos/myAccountName/repo/git/trees/' + hash;
objectedJSON = makeAJAXCall(hash, function (objectedJSON) {
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));
}
}
});
console.info(objectList);
return objectList;
}
$(document).ready(function () {
var objects = walkTree('master', function () { // master to start at the top and work our way down
console.info(objects);
});
});
Here you are making an
AJAXcallArefers to asynchronous, ie your success/error callback will be executed asynchronously.makeAJAXCall will return before executing success/error of $ajax.
so the
objectedJSON = makeAJAXCallwill return youundefinedNow when you call makeAjaxCall the callback function you are passing will exist in the closure scope of $.ajax and will be executed on success of server response
check below links
https://developer.mozilla.org/en/JavaScript/Guide/Closures
https://mikewest.org/2009/05/asynchronous-execution-javascript-and-you
or you can make your ajax call in sync using
async:falsewhich is highly not recommendedIn the above case your code will work