jquery promise deferred ajax call demo

jquery promise deferred ajax call demo

by stratdaz

HTML

<h1>wait for ajax call completion</h1>

CSS

html,
body {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

JavaScript

(function() {
  var restante = 0;
  secondfunction();
})();

function firstfunction(){
	var dfd = jQuery.Deferred();
 	dfd.notify( "making ajax call " );
  
  $.ajax({
        url:'/echo/jsxx/?js=Data returned from promise',
        complete: function (response) {
            $('h1').html();
						$("h1").text("first");
            
            console.log(response);
            
            dfd.resolve( response.responseText); 
        },
        error: function () {
            $('h1').html('Bummer: there was an error!');
        },
    });
    
	return dfd.promise();
};

function secondfunction(){
	$.when(firstfunction()).then(
		function(text){$("h1").text( text+ " - success");},
		function(text){$("h1").text( text+ " fail");},
		function(text){$("h1").text( text+ " - waiting ");}
	);
};