async ajax calls and waiting on responses with knockout

668 views
Skip to first unread message

Charles Kaiman

unread,
Mar 11, 2013, 4:53:38 PM3/11/13
to knock...@googlegroups.com
I have two ajax calls to get rather large batches of json data.  Both of these calls must be returned prior to a third ajax call, which is a much faster query.  Can anyone recommend a good practice for ensuring that 2 ajax calls have been returned, perhaps using knockout?

My initial thought is to create a variable, set it to 0, and initiate a count, and wrap it in a WHILE loop.  But I'm concerned that this will lock my UI for too long.

var i = 0;

ajax 1
{
  success: i++; 
}

ajax 2
{
  success: i++;
}

while (i < 2)
{
  ajax 3
  {
  }
}

Can anyone recommend a better way?  I was looking at throttling in knockout, but couldn't manage to figure out if it would help in this case?

Charles Kaiman

unread,
Mar 11, 2013, 5:01:22 PM3/11/13
to knock...@googlegroups.com
UPDATE:  slight correction on my 'while' logic
do
{
 if (i == 2)
   ajax 3 { i++ }
}
while ( i <= 2)
Message has been deleted

Miguel Castillo

unread,
Mar 11, 2013, 5:43:06 PM3/11/13
to knock...@googlegroups.com
What I strongly recommend to use some sort of promise provider.  For example, jQuery returns promise objects when you make ajax calls.  If you use something like jQuery, you can do something like the following.

//
// all ajaxCall are jQuery ajax calls, which return a promise object.
//
$.when( ajaxCall1, ajaxCall2 ).pipe(function(result1, result2){
   return ajaxCall3.done(function(result3){
      // handle last bit of ajax.
   });
});

Checkout jQuery's documentation for $.when and pipe.  Pipe is a bit obscure to follow, but the example will get you started.  There are other tools that give you promise functionality such as promisejs.


Thanks,
Miguel

Charles Kaiman

unread,
Mar 11, 2013, 5:59:58 PM3/11/13
to knock...@googlegroups.com
Thank you Miguel, I decided to use SetInterval() for now, and it is working for me...but will definitely give the promise provider a close look!!

Charles Kaiman

unread,
Mar 13, 2013, 1:07:03 PM3/13/13
to knock...@googlegroups.com
Thanks again Miguel.  I moved over to chaining with $.when and promises.  Thank for the heads-up!


On Monday, March 11, 2013 5:43:06 PM UTC-4, Miguel Castillo wrote:
Reply all
Reply to author
Forward
0 new messages