2

I'm trying to follow some javascript lessons where there is an implementation of Deferred. This is the core of the code

getData = function (options) { return $.Deferred(function (def) { var results = options.results; getFunction({ success: function (smt) { results("test"); def.resolve(results); debugger; }, error: function (response) { def.reject(); } }); }).promise(); }, 

Now the question is.. when i call this function from outside like:

$.when(somthing.getData(options)). done(alert(options.results)); debugger; 

It happens that FIRSTLY reach the debugger outside the $.when call, and THEN touch the one inside callback SUCCESS function inside the Deferred object...

I don't get it.. shouldn't be the promise done only when def.resolve(results) is reached?...

1 Answer 1

1

Everything's correct except for the last line:

$.when(somthing.getData(options)).done(alert(options.results)); debugger; 

You call alert ( and debugger ) immediatly here. What you want is to pass a callback to done like this:

$.when(somthing.getData(options)) .done(function(){ alert(options.results); debugger; }); 
Sign up to request clarification or add additional context in comments.

2 Comments

Thank freakish.. that worked like a charm.. Can i ask you why?.. I thought that the function inside DONE was already a callback function... why do i have to define a function like that to call my function?...
.done accepts a function. What you passed to .done is not a function, but a result of calling alert() ( note the order: first alert is called, then it's result is passed to .done ) which is undefined ( that's what alert returns ). It's like doing .done("test"). What does it mean? What JavaScript is supposed to do with a string? You want to pass a function to .done, so JavaScript will know: "oh, I've received a function, I can call it once when is done".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.