Question

I've a method with 4 subsequent ajax calls, which look like:

$.ajax({
    success: function( response ){
        $.ajax({
            success: function( response ) {
               ..more calls deeper..
            },
            error: function( ) {
                showError();
            }
        });
    },
    error: function( ) {
        showError();
    }
});

Is there any pattern to chain all thouse calls without nesting and duplicating error callback?

Was it helpful?

Solution

Something like this:

$.when(
  // first one
  //data = data1
  $.get("your-url-1-here"),

  // second one
  // data = data2
  $.get("your-url-2-here"),

  // third one
  //data = data3
  $.get("your-url-3-here"),

  // fourth one
  // data = data4
  $.get("your-url-4-here")

).then(function( data1, data2, data3, data4 ) {

  //Do something with data1, data2, data3 and data4

});

OTHER TIPS

Regarding the duplication of the error callback, just point to the showError function like this:

error: showError

No need to wrap it in a function there

var flagIsFinished = false;
function ajax(successCB, errorCB){
  if(!flagIsFinished){
    $.ajax({
      'success':function(){
        ajax(successCB, errorCB);
      }
      'error':errorCB
    });
  }
}

Work with a flag. Set it true in the successCB when you're finished. Like this you'll never have to worry how many times you have to run the ajax function, just make sure you test the end condition very well. Otherwise you could get an endless loop with this approach.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top