I want to make sure I understand callbacks properly, and javascript timing etc. in general.
Say my code looks like this, is it guaranteed to execute in order?
SetList(); // initializes the var _list
Some.Code(_list, function(data) {
// update list
});
DoSomething(_list); // operates on _list
Update
What I am seeing is SetList calls, then DoSomething, then Some.Code.
Some.Code calls another function. so:
Some.Code(_list, function() {
//load _list from ajax request
Other.Code.WithCallback(_list, function(){....});
});
I guess to fix this, I have to add DoSomething to the inner function as another callback?
SetList(),Some.Code()andDoSomething()will execute in that order, one after the other. The anonymous function passed as the second argument toSome.Code()could be called during the execution ofSome.Code()(before the function returns andDoSomething()is called) or it could be called at a later time by another function, and event handler or timer, it all depends on when you specified it to be called.Since you’re using ajax, the request to the remote server is made on a separate thread, so the executing javascript thread continues to run and call other functions until a response (or, more specifically, for the
onreadystatechangeevent to fire). When the ready state of the ajax request changes, itsreadystatechangeevent handler is queued to be called — meaning it will execute as soon as all currently executing scripts finish.If you want
DoSomething()to execute after the response is received via ajax, you should run it to the end of your callback function instead.