I have several lines in my code that need to be run in the right order. These lines include:
Ajax calls, Animations, and Playing Audio
I am aware of these questions: Call a function after previous function is complete
Wait until all jQuery Ajax requests are done?
How do I make jQuery wait for an Ajax call to finish before it returns?
I just need a way that I can add to the function definition so that the function would be completed first before any other action is done. My major problem is with this function1.done(function2) or the callback structure, because I have many of these, so I would want to control the sequence of execution of these lines just with their order in the code. Is there a way to do that?
$.get(lang1_txt_path, function(data) {
src_txt = data;
}, 'text').done(function() {
$.get(lang2_txt_path, function(data) {
trg_txt = data;
}, 'text').done(function() {
$.get(lang2_os_txt_path, function(data) {
trg_txt_os = data;
}, 'text').done(function() { //something
})
})
});
and these are the animations:
$("#success_div").delay(1000).show(1000);
$("#success_div").delay(500).hide(500);
$("#success_div").fadeOut('slow', function() {
//something else
});
and this for the audio:
function play_audio(audio_path,audio_type){
audio = document.getElementById("audio_"+audio_type);audio.src =audio_path;audio.play();
}
play_audio(audio_path1,'general')
played_2nd_file=false;
$("#audio_player").bind("ended", function(){
if (played_2nd_file==false){
audio_path2="audio/"+lang2+'.'+trg_audio2
play_audio(audio_path2,'general')
console.log(audio_path2)
played_2nd_file=true;
}
});
So, you can see, it is much hassle to make each of these wait till the previous ones are completed. Maybe there can be some good programming practices regarding how to organize them and include callbacks, but it is just so complicated, given that the code is changing very fast, so the only way is to make sure the functions are implemented in their same order within the code, so that this would be included in the definition of each function. Ideally I want something like:
ajax_load_file(file_path1)
ajax_load_file(file_path2)
ajax_load_file(file_path3)
play_success_animation()
play_success_audio()
play_transition_audio()
play_transition animation()
Thank you so much!