Reputation: 4169
I have this piece of code:
Event = new Event();
// Create a deferred object
var dfd = $.Deferred();
// Add handlers to be called when dfd is resolved
dfd.done( Event.getEvents( position.coords.latitude, position.coords.longitude ) ).then( function( data ){
//rest of the code ..
console.log("No!");
});
That doesn't behave the way I want. the done is never resolved and the then()
is never triggered. Here is Event.getEvents
(its in another file):
function Event() {
this.getEvents = function( lat, lng )
{
var d = new $.Deferred();
console.log("events");
var key = getCookie("key");
$.ajax({
type:"GET",
url: server_url + 'event/eventssurrounding',
headers: { 'X-API-KEY': key },
data: { lat:lat, lng: lng, radius: radius, limit: limit, offset: offset },
dataType: 'json',
success : function(results) {
console.log('success');
d.resolve = results.map( function ( event ) {
console.log(event);
var dist = JSON.stringify(event.distance);
console.log(dist);
return {
id: event.id,
name: event.name,
type: event.type,
desc: event.desc,
short_desc: event.desc.substring(0,200),
pic: event_pic_url + event.picture,
place: {
id: event.placeId,
name: event.placeName,
type: event.placeType
},
dist: dist.substring(0,3),
lat: event.latitude,
long: event.longitude,
}
});
console.log("done");
return d.promise();
},
error : function( xhr, type )
{
return null;
}
});
console.log("This shouldn't be logged before success.");
}
};
I'd like the the console.log("No!")
(in first piece of blog) to be triggered AFTER the AJAX call. But from what I see in my console log, the ajax call is executed after the "This shouldn't be logged before success." is logged. And the done is never triggered. I can't find out why.
here is my log:
events
This shouldn't be logged before success.
success
Object
2.3322972250333
done
If I try with $.when(Event.getEvents()
... then the done is triggered immediately after "This shouldn't be logged before success."
How can I have my deferred object to be triggered after the AJAX call is over, when I return a promise ?
Thanks
Upvotes: 2
Views: 246
Reputation: 7445
Your code is quite strange: you are tryig to pass a result of getEvents
function to $.when
(which should accept jQuery deferred objects), but getEvents
has no return statement at all.
$.when
gets undefined
and has nothing to do actually. I guess your getEvents
function might return a result from ajax call like this:
this.getEvents = function( lat, lng )
{
// ... code
return $.ajax({
// ....
});
}
I think this might be just a part of solution, but I believe it is a good start.
Next thing, why do you think this:
console.log("This shouldn't be logged before success.");
souldn't be executed before success? You started an async call and next statement is console.log
. JS is single threaded and there is no chance that ajax call will finish work before this log
call. This has no sence.
Next, what is the following code?
d.resolve = ....
Isn't it should like
d.resolve ( // ... );
?
Upvotes: 2