Search code examples
javascriptjqueryajaxasynchronouscoordinate

Why can't / shouldn't I use a while loop to monitor asynchronous jQuery operations?


I am trying to wrap my head around coordinating asynchronous operations. I need a little help understanding:

  1. Why using a while loop to wait for an operation to complete is a bad idea and doesn't work, and
  2. If there are viable alternatives to using callbacks on the jQuery functions

Most of the time, adding a callback to an asynchronous function like $.get() works great. However this does, to some degree, dictate how & where my code is written which I don't love.

$(function() {

    var r = AjaxResults( page );

    // loop prevents further processing until GetResults() is done
    while( isComplete == false )
    isComplete = $('body').data('isComplete');

    // reset isComplete boolean
    $('body').data('isComplete', false);

    // this will only continue after GetResults() has exited
    paintTheTownRed();
    var whateverElse = true;
});

function AjaxResults( page ) {

   // do something before async operation
   switch( page ){
       case '1': {...} break;
       ...
       default: break;
   } 

   $.getJSON("/controller/page", null, function(data) {

       // do something after async operation
       {...}

       $('body').data('isComplete', true);
       return data;
   });
}

Solution

  • Because it will spike my CPU and irritate me greatly.

    Where you write your code is almost never dictated by asynch/synch; functions are functions, whether they're anonymous and written in-line, or named and passed as a reference.

    Also, promises and deferred objects help in deciding where/how to implement functionality.

    See things like .when (docs) for additional details and ideas, but there are other ways to use them.