Ivan_nn2
Ivan_nn2

Reputation: 469

Callback function inside Deferred objects

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?...

Upvotes: 2

Views: 676

Answers (1)

freakish
freakish

Reputation: 56477

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;
});

Upvotes: 1

Related Questions