'A wrapping long running JavaScript code into really async javascript function without await
I want multiple synchronous ajax calls to run at page load in background (in an asynchronous function without await) and let the page load for user without any wait. I have added my hacky solution, but want to know that how JavaScript already provides a real/formal solution for the given problem
let dt_pl = new Date();
function time_taken_to_reach_here(){
let diff_ms = new Date() - dt_pl;
return diff_ms;
}
$(function(){
console.log('page loaded ', time_taken_to_reach_here());
// Time in milliseconds
// 132 when non_async
// 139 when not_really_async
// 160 when hacky_async_back_ground
});
Above time is also shared as images in end of question. Following is the code for different methods to execute bunch of ajax calls. Question is not about having alternative approach to solve specific problem, but actually only wrapping long running JavaScript code into really async
function ajax1(){
$.ajax({ url: '/read_thing_information_schema', success: function(data){ /* use data */}});
}
function ajax2(){
$.ajax({ url: '/read_other_information_schema', success: function(data){ /* use data */}});
}
function non_async(){
console.log('Function used => non_async');
console.log('starting ajax calls ', time_taken_to_reach_here());
ajax1(); ajax2(); after_tables_loaded();
console.log('all called and call backs done ', time_taken_to_reach_here());
}
function not_really_async(){
console.log('Function used => not_really_async');
(async function(){
non_async();
})();
}
function hacky_async_back_ground(){
console.log('Function used => hacky_async_back_ground');
console.log('starting ajax calls ',time_taken_to_reach_here());
$.ajax({
url: '/dummy_path_that_actually_does_not_exist',
complete: function(){
ajax1(); ajax2(); after_tables_loaded();
console.log('all call backs done ',time_taken_to_reach_here());
}
});
console.log('all called ',time_taken_to_reach_here());
}
Calling one of above methods
// hacky_async_back_ground();
// non_async();
not_really_async();
Results
called non_async function
called not_really_async
called with hacky_async_background
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|



