Search code examples
javascriptjqueryajaxchain

A pattern to call sequence of ajax calls?


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?


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
    
    });