Best way to add a 'callback' after a serie

2019-01-26 02:01发布

I stumbled on a piece of Ajax code that is not 100% safe since it's mixing asynchronous/synchronous type of code... so basically in the code below I have a jQuery.each in which it grabs information on the elements and launch an Ajax get request for each:

$(search).each(function() {
 $.ajax({
  url: 'save.x3?id='+$(this).attr("id")+'value='$(this).data("value");
  success: function(o){
   //Update UI
  },
  error: function(o){
   //Update UI
  }
 });
});

//code to do after saving...

So obviously the 'code to do after saving...' often gets executed before all the requests are completed. In the ideal world I would like to have the server-side code handle all of them at once and move //code to do after saving in the success callback but assuming this is not possible, I changed the code to something like this to make sure all requests came back before continuing which I'm still not in love with:

var recs = [];
$(search).each(function() {
 recs[recs.length] = 'save.x3?id='+$(this).attr("id")+'value='$(this).data("value");
});

var counter = 0;
function saveRecords(){
 $.ajax({
  url: recs[counter],
  success: function(o){
   //Update progress
   if (counter<recs.length){
    counter++;
    saveRecords();
   }else{
    doneSavingRecords();
   }
  },
  error: function(o){
   //Update progress
   doneSavingRecords(o.status);
  }
 });
}

function doneSavingRecords(text){
 //code to do after saving...
}

if (recs.length>0){
 saveRecords();  //will recursively callback itself until a failed request or until all records were saved
}else{
 doneSavingRecords();
}

So I'm looking for the 'best' way to add a bit of synchronous functionality to a series of asynchronous calls ?

Thanks!!

4条回答
Deceive 欺骗
2楼-- · 2019-01-26 02:09

This is easily solved by calling the same function to check that all AJAX calls are complete. You just need a simple queue shared between functions, and a quick check (no loops, timers, promises, etc).

    //a list of URLs for which we'll make async requests
    var queue = ['/something.json', '/another.json']; 

    //will contain our return data so we can work with it
    //in our final unified callback ('displayAll' in this example)
    var data = [];

    //work through the queue, dispatch requests, check if complete
    function processQueue( queue ){
        for(var i = 0; i < queue.length; i++){
            $.getJSON( queue[i], function( returnData ) {
                data.push(returnData);

                //reduce the length of queue by 1
                //don't care what URL is discarded, only that length is -1
                queue.pop();

                checkIfLast(displayAll(data));
            }).fail(function() {
                throw new Error("Unable to fetch resource: " + queue[i]);
            });
        }
    }

    //see if this is last successful AJAX (when queue == 0 it is last)
    //if this is the last success, run the callback
    //otherwise don't do anything
    function checkIfLast(callback){
        if(queue.length == 0){
            callback();
        }
    }

    //when all the things are done
    function displayAll(things){
        console.log(things); //show all data after final ajax request has completed.
    }

    //begin
    processQueue();

Edit: I should add that I specifically aimed for an arbitrary number of items in the queue. You can simply add another URL and this will work just the same.

查看更多
Lonely孤独者°
3楼-- · 2019-01-26 02:12

>> In the ideal world I would like to have the server-side code handle all of them at once and move //code to do after saving in the success callback

You'll need to think about this in terms of events. Closure's net.BulkLoader (or a similar approach) will do it for you:

See: goog.net.BulkLoader.prototype.handleSuccess_ (for individual calls) & goog.net.BulkLoader.prototype.finishLoad_ (for completion of all calls)

查看更多
三岁会撩人
4楼-- · 2019-01-26 02:13

Better Answer:

function saveRecords(callback, errorCallback){
  $('<div></div>').ajaxStop(function(){
    $(this).remove(); // Keep future AJAX events from effecting this
    callback();
  }).ajaxError(function(e, xhr, options, err){
    errorCallback(e, xhr, options, err);
  });

  $(search).each(function() {
    $.get('save.x3', { id: $(this).attr("id"), value: $(this).data("value") });
  });
}

Which would be used like this:

saveRecords(function(){
   // Complete will fire after all requests have completed with a success or error
}, function(e, xhr, options, err){
   // Error will fire for every error
});

Original Answer: This is good if they need to be in a certain order or you have other regular AJAX events on the page that would affect the use of ajaxStop, but this will be slower:

function saveRecords(callback){
  var recs = $(search).map(function(i, obj) {
   return { id: $(obj).attr("id"), value: $(obj).data("value") };
  });

  var save = function(){
   if(!recs.length) return callback();

   $.ajax({
    url: 'save.x3',
    data: recs.shift(), // shift removes/returns the first item in an array
    success: function(o){
     save();
    },
    error: function(o){
     //Update progress
     callback(o.status);
    }
   });
  }

  save();
}

Then you can call it like this:

saveRecords(function(error){
   // This function will run on error or after all 
   // commands have run
});
查看更多
成全新的幸福
5楼-- · 2019-01-26 02:27

If I understand what you're asking, I think you could use $.ajaxStop() for this purpose.

查看更多
登录 后发表回答