I have little doubt, I have let say 5 or more js functions each calls C# functions Via Ajax calls doing various task like(fetching data from the database, validating it, calculations, saving it back to The database etc).
I am calling the function using Nested jQuery $.when(function1()).then(function2())
and so on. I want function one to fully complete before two and two before the third one and so one…. there are some dependency between these functions…
My Code example Like: (My Approach)
$(document).ready(function () {
$.when(one()).then(
$.when(two()).then(
$.when(three()).done(alert('three done')).then(
$.when(four()).then(
five()
).done(alert('All Finished Up'))
)
)
)
});
function one() //eg List 1000 records from Db
function two() //Update Some
function three() //validate Changes
function four() //save Changes
function five() // Some Other Task then
Now my question is simple I know rather than calling sequentially like
$(document).ready(function(){
one();
two();
three();
four();
five();
});
I used above nesting pattern (My Approach)… Is that good approach coding-wise and performance wise? Is there any more efficient approach than this?
2
Answers
There is: if you want to only support browsers that support ES6, you can simply use the async/await syntax, as the jQuery Promises return a native
Promise
object anyway:Alternatively, you can run all of those calls in parallel to get a faster return