JQuery promises

- how the browser runs the js code

- how to make a request to the server

- what are callbacks

- what is a promise

- how we should use them

A callback function, also known as a higher-order function, is a function that is passed to another function (let’s call this other function “otherFunction”) as a parameter, and the callback function is called (or executed) inside the otherFunction. A callback function is essentially a pattern (an established solution to a common problem), and therefore, the use of a callback function is also known as a callback pattern.

Callbacks

Text

Callbacks

$("#btn_1").click(function() {
  alert("Btn 1 Clicked");
});


----------------------------------


var friends = ["Marcel", "Ion", "Nume", "Robi"];
​
friends.forEach(function (eachName, index){
console.log(index + 1 + ". " + eachName)
});

Requesting data

$.ajax({
    type: "GET/POST/PUT",
    url: "api/something",
    success: function( data ){
    },
    error: function() {
    }
});

Requesting data

Deffer object

The Deferred object, introduced in jQuery 1.5, is a chainable utility object created by calling the jQuery.Deferred() method. It can register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.

 

Requesting data

$.ajax({  url: "test.html" })
 .done(function(data){
  alert('ajax request was successful');
  })
 .fail(function(data){
  alert('ajax request failed');
 });
  

Requesting data

$.when($.ajax("mypage1.html"), $.ajax("mypage2.html")).done(function(a1,  a2){
     $('div.page1details').html(a1[0]);
     $('div.page1details').html(a2[0]);
  });
Made with Slides.com