'Debugging ajax flow
I am really confused on a program that I made. A few days ago, it was working just fine, but now I am having problems with initializing it. I think I've figured out the source of the problem is basically the flow of the program is out of order but I have no idea why. Anybody have any idea how to debug this?
Debug Call Stack:
This
function init() {
createKeyArray();
createData();
}
Or this (createKeyArray)
function createKeyArray(){
$.getJSON("reps.json", function(data) {
$.each(data, function(key, val) {
console.log(key);
keyarray.push(key);
});
})
.fail(function(){
console.log("JSON extraction failed.");
});
};
Now during this period on the createKeyArray
this is where it gets really confusing, it goes to .getJSON
, runs it, then goes to my createData
function (skipping the $.each
function that pushes everything into keyarray.
It then runs createData
then goes BACK to the .each
part of createArray
function, runs that and then finishes running the rest of the program.
I am extremely confused whats going on and how to solve it. Appreciate any advice.
Solution 1:[1]
I got it but thanks for the help everyone. I was just confused over how async worked. I had looked it up before posting this but I guess I ultimately didn't understand how it worked. The .getJSON method I redid, and this time I made it
function createKeyArray() {
$.ajax({
url: "sdf.json",
dataType: 'json',
async: false,
success: function(data) {
$.each(data, function(key, val) {
keyarray.push(val);
});
}});
}
To be honest, I'm still not quite certain how the runtime for async operations works. I guess what I'm hinting at is if anybody could enlighten me how how the computer determines when to run the call back function on an asynchronous call, I would appreciate the insight. Otherwise, the above code is the answer.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | General Grievance |