1

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?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • @Terry thanks for answering.. currently i am bound to use Es5.....want to know about if this approach is good or bad.. for impleting in the project i am working on... thanks – Khan Faizan Apr 22 '20 at 18:01
  • If all your function are synchronous (ie. will execute in order) calling them sequentially is fine. Otherwise, a synchronisation mechanism (like callbacks or 'promises') is needed. The callback pattern leads to heavily indented hard-to-read source code and misses the underlying abstraction of a value available in the future. The modern approach thus uses 'promises', just as jquery does with `when` (or `async`/`await`, which is essentially a shorthand notation). – collapsar Apr 22 '20 at 18:04
  • @collapsar thanks for answering... My function calls are asynchronous.........using ajax..calls – Khan Faizan Apr 22 '20 at 18:08
  • Linked - https://stackoverflow.com/a/5627301/104380 – vsync Apr 22 '20 at 18:27

2 Answers2

0

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>
Terry
  • 63,248
  • 15
  • 96
  • 118
0

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>
zeachco
  • 754
  • 4
  • 16