I know, using the words JavaScript and 'atomic'-anything in the same sentence is kinda strange, since JavaScript is prised to be asynchronous and therefor not very atomic.
//EDIT This was a mistake on my side! by having alert's going off (and hiding further alerts in chrome) it quickly interrupted and let other code fly. JavaScript is single-threaded.
Quick -> Actual Question; in which situation are we save from async callback interrupts and how could we prevent them for certain code blocks?
Long -> My Scenario; My whole application is very recursive and triggers many ajax requests, that on returns, triggers many more recursive functions that may trigger more ajax requests. In my Code, I have some very crucial operations on an array, that have to complete before the next operation can happen (simple push/splice logic though).
I had a problem, where I got the index of a key within an array and saved it in a variable. I then compared it to -1 and if it was true, I spliced (not just unset) the element from the array. Now, in between getting the index and splicing, the asynchronous callback returned with results and started recursive stuff, which then altered the array by adding/removing further items (and messing up the index value I got before).
This was the old code;
if ( this.dataset && (index=this.dataset.children.indexOf(child.key) )!==-1 ){
console.log("removed from dataset!");
//<=== AJAX Call Returns and adds/removes items from the array
this.dataset.children.splice(index, 1); //goes bad, because index not good anymore
...
}
and this is the 'working', but not optimized code
if ( this.dataset && (index=this.dataset.children.indexOf(child.key) )!==-1 ){
console.log("removed from dataset!");
//<=== AJAX Call Returns and adds/removes items from the array
//Problem solved, since I'm getting the index again
this.dataset.children.splice(this.dataset.children.indexOf(child.key), 1);
...
}
I just simply search for the index again and directly splice it away.
my general question is, in which situation are we save from async callback interrupts and how could we prevent them for certain code blocks?
My specific question, fellow StackOverflowers, is if in theory, the ajax callback could be called in between the indexOf function returning the index and the splice function cutting the array up.
Thank you for your help
p.S I am aware, that I just could unset the array field and my index problem would be solved. But that's not what I want, since I'm serialising that information and don't want 100ths of empty entries. Finding a general way how to tackle such situations is my goal :)