Promises

Promises – uses same ajax call on multiple pages
var promise = $.Deferred(); – create a new promise object
promise.resolve(value); – calls the done callback: promise.done(function(value){ });
promise.reject(value); – calls the fail callback: promise.fail(function(value){…});
$.when(promise1, promise2…) – takes any number of promises
.then(function(p1Data, p2Data){}); – promises callback data in the same order

London, UK

Update Price
Promise 1
var Vacation = {
  getPrice: function(location){
    var promise = $.Deferred();
    $.ajax('/vacation/prices', {
      data: {q: location},
      success: function(result){
        promise.resolve(result.price);
      },
      error: function(){
        var error = 'invalid location';
        promise.reject(error);
      }
    });
    return promise;
  }
}
$(document).ready(function() {
  $('button').on('click', function(){
    var location = $('.location').text();
    Vacation.getPrice(location).done(function(result){
      $('.price').text(result);
    }).fail(function(error){
      console.log(error);
    });
  });
});

 

 

<ul>
  <li data-location="london, uk">
    London, UK
    <button>More Info</button>
    
</li> <li data-location="paris, france"> Paris, France <button>More Info</button>
</li> <li data-location="new york, ny"> New York, NY <button>More Info</button>
</li> </ul>
Promise 2
var Photo = {
  getPhoto: function(location){
    var promise = $.Deferred();
    $.ajax('/vacation/photos', {
      data: {q: location},
      success: function(result){
        promise.resolve(result.url);
      }
    });
  return promise;
  }
}
Ajax Result
{
 price: 2600
}
$(document).ready(function() {
  $('button').on('click', function(){
    var tour = $(this).parent();
    var location = tour.data('location');
    var resultDiv = tour.find('.results').empty();
 
   $.when(
     Vacation.getPrice(location),
     Photo.getPhoto(location)
   ).then(function(priceResult, photoResult){
     $('<p>$'+priceResult+'</p>').appendTo(resultDiv);
     $('<img />').attr('src', photoResult).appendTo(resultDiv);
     });
  });
});
Advertisements

About bernadetteengleman

Hello, I am Bernadette from New York City. I moved here from Chicago in 2013. I am originally from the Philippines. I started studying web programming in 2015. I love it because I like making fun websites and web apps. The projects that I built so far are posted below. I like to cook and I love to travel. I also like to volunteer and I am a team leader with the non-profit organization, NYCares.
This entry was posted in jQuery. Bookmark the permalink.