I have not used deferreds before but I’ve read a bit here and there on them and from my understanding, it sounds like they’d be a solution to a current problem I’m having. I have a page that has to load 4 ads on it. Previously the page was slowing down due to the time it would take the server to query the database for each ad. So I moved the banner ad calls to a web service. This worked fine however if I have no ads I need to hide the container div so that means I need to know when all the ajax calls have completed and then check to see if any ads were loaded.
I have the following code that successfully calls the web service and loads the ads but it doesn’t appear that the then() function is working right. It seems to be executing before the ajax calls complete. I got my code from this page JQuery deferred with .each() and the only difference I can see is that in their example, it shows returning the function call within the deferred. But I’ve tried surrounding my function innerds with return{} but it just throws an error (Unexpected token “=”). Can anyone tell me what I’m doing wrong? Thanks.
var deferreds = $(".ad").map(function () {
var t = $(this);
$.ajax({
type: "POST",
url: "/Services/Services.asmx/GetBanner",
data: "{'bannerId':" + t.attr("bannerid") + ",'siteId':" + sid + ",'dt':'" + new Date().toString() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json"
})
.success(function(data) {
if (data.d.Banner != null && data.d.Banner != undefined) {
t.html("<div class=\"featuredAd\">" + data.d.Banner + "</div>");
}
});
});
$.when.apply(null, deferreds.get()).then(function () {
if($(".featuredAd").length > 0)
$("#dvFeaturedBottom").show();
});
You didn’t return the promise objects.