tags:

views:

56

answers:

2

Note: Sorry for the amount of pseudo code below, but I didn't know how else to show what I'm trying. There is actually a lot more code than that in my solution that manages ajax icon's and status, but I've dumbed it down to show the root of my problem.

Basically, I'm trying to create a process loop on a web page and I'm finding it to be very difficult. What I would like to do is display a list of transactions. At the top of the page, I want to present the user with a 'Process All' button which will process each transaction one at a time. While a transaction is being processed on the server, the user should be able to cancel the process loop. This would simply stop the NEXT transaction from being sent; very simple cancel. However, due to the asynchronous nature of ajax calls, I'm struggling quite a bit. :(

I have it working great in a synchronous loop. However, the user is not able to click the cancel button using the synchronous approach due to the single threaded nature of it. Here is what I have concocted in an attempt to manage this in an asynchronous loop:

<a href="#" id="processAll">Process All</a>
<a href="#" id="cancelProcess">Cancel</a>
<table>
  <tr><td><a href="#" id="processLink1">Process</a></td></tr>
  <tr><td><a href="#" id="processLink2">Process</a></td></tr>
  <tr><td><a href="#" id="processLink3">Process</a></td></tr>
  <tr><td><a href="#" id="processLink4">Process</a></td></tr>
</table>

Below is what the code looks like that handles the above links:

var currentId = null;
var isWaiting = false; 
var userCancel = false;

$("#processAll").click(function(){

  $(this).hide();
  $("#cancelProcess").show();

  userCancel = false;

  // NOTE: this is where I think I need more logic...?

  processNextTransaction();

});

$("#cancelProcess").click(function(){

  $(this).hide();
  $("#processAll").show();

  userCancel = true;

});

$("a[id ^= processLink]").click(function(){

  var id = $(this).attr("id").replace(/^processLink(/d+)$/, "$1");
  doTransaction(id);

});

Below are the helper methods that I use in the three delegates above:

function processNextTransaction()
{

   var anchorId = $("a[id ^= processLink]:first").attr("id");
   var id = anchorId.replace(/^processLink(/d+)$/, "$1");

   function check() 
   {
     if (isWaiting)
       setTimeout(check, 500);
     else
     {
       if (!userCancel)           
         doTransaction(id);
     }
   }
   check();
}

function doTransaction(id)
{
   isWaiting = true;
   currentId = id;

   $.ajax({
       type: "POST",                
       url: "/Transactions/Process/" + id,
       data: {},
       success: successHandler,
       error: failHandler
   });

}

function successHander(result)
{
   // handle result...
   $("#processLink" + currentId).replaceWith(result);
   isWaiting = false;
}

function failHandler(result)
{
   alert("Error: " + result);
   $("#processLink" + currentId).replaceWith("Error!");
   isWaiting = false;
}

Notice that I only call processNextTransaction() one time, and this is really my main problem. I considered doing it from the successHandler and failHandler, but that defeats the purpose of the setTimeout & isWaiting flag, and also causes other problems when the user clicks on a single 'Process' link to process a single transaction. This is my first experience with an ajax looping scenario... Please help! :)

What is the suggested approach for managing a list of processes in an asynchronous environment?

+3  A: 

This should work:

<a href="#" id="processAll">Process All</a>
<a href="#" id="cancelProcess">Cancel</a>
<table>
  <tr><td><a href="#" class="processLink" id="pl_1">Process</a></td></tr>
  <tr><td><a href="#" class="processLink" id="pl_2">Process</a></td></tr>
  <tr><td><a href="#" class="processLink" id="pl_3">Process</a></td></tr>
  <tr><td><a href="#" class="processLink" id="pl_4">Process</a></td></tr>
</table>

And the jQuery magic:

var cancel = false;

$('#processAll').click(function() {    
    process($('.processLink:first'), true);
    cancel = false;
    return false;
});

$('.processLink').click(function() {
    process($(this), false);
    return false;
});

$('#cancelProcess').click(function() {
    cancel = true;
    return false;
});

function process(el, auto) {

    if(!cancel) {
        var id = parseInt(el.attr('id').replace('pl_', '')); // Get numeric ID

        $.ajax({
           type: "POST",                
           url: "process.php?id=" + id,
           success: function() {
               el.html('Processed');                     
               if(auto) { // If auto is true, process next ID                        
                   if($('#pl_'+(id + 1)).size() > 0) {                             
                       process($('#pl_'+(id + 1)), true);
                   }
               }
           }
       });
    }
}

The process function uses the success handler to process the next element, if the original process function was called with the variable automatic set to true.

The cancel won't cancel the process if it has already started, obviously.

You might have/need different kind of methods to traverse your process items, but I guess that's not your problem (this relies on the ID's being in numerical ascending order).

A working example can be found here: http://www.ulmanen.fi/stuff/process.php

Tatu Ulmanen
Thank you for your thorough response and online running example (wow). I took your advice and basically moved my 'successHandler' and 'failHandler' to the ajax definition as inline methods instead of stand alone functions. My project is working great now, and cancel works! Thanks again.
Luc
A: 

Your code is too long to read, but based on your introduction, I'd do something like this:

Create a queueing mechanism (basically an array). When the user wants a transaction to be processed, add it to the queue, and call a function that does something like doNextItemInQueue_unlessSomethingAlreadyRunning().

That function takes the first item in the queue (an url, basically), makes an ajax request, waits for a response, and then calls itself again.

If you want to enable aborting the queue, allow a flag (e.g. abort_queue) to be set, and check it before doNextItemInQueue_unlessSomethingAlreadyRunning() is run.

Joel L