skip to Main Content

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


  1. 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:

    // Dummy async operation
    function sleep(t) {
      return new Promise(resolve => setTimeout(resolve, t));  
    }
    
    $(document).ready(function() {
      run().then(() => console.log('all done'));
    });
    
    // Run all your async functions sequentially
    async function run() {
      await one();
      console.log('one done');
      await two();
      console.log('two done');
    }
    
    async function one() {
      return sleep(500);
    }
    async function two() {
      return sleep(500);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    Login or Signup to reply.
  2. Alternatively, you can run all of those calls in parallel to get a faster return

    function sleep(ms) {
      return new Promise((resolve) => setTimeout(resolve, ms));
    }
    
    async function one(mode) {
      await sleep(1000);
      console.log(`${mode} : one() finished`);
    }
    
    async function two(mode) {
      await sleep(3000);
      console.log(`${mode} : two() finished`);
    }
    
    async function three(mode) {
      await sleep(3000);
      console.log(`${mode} : three() finished`);
    }
    
    async function four(mode) {
      await sleep(4000);
      console.log(`${mode} : four() finished`);
    }
    
    async function five(mode) {
      await sleep(5000);
      console.log(`${mode} : five() finished`);
    }
    
    async function runInSerial() {
      await one('serial');
      await two('serial');
      await three('serial');
      await four('serial');
      await five('serial');
    }
    
    async function runInParallel() {
      await Promise.all([
        one('parallel'),
        two('parallel'),
        three('parallel'),
        four('parallel'),
        five('parallel'),
      ]);
    }
    
    $(document).ready(function () {
      runInSerial().then(() => console.log('serial : all done!'));
      runInParallel().then(() => console.log('parallel : all done!'));
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search