Aragorn
Aragorn

Reputation: 5289

jQuery Deferred promise then

New to the JavaScript Promises and having tough time grasping the concept. It seemed I finally understood, but can't seem to get it working.

Here's a simple try:

first = function(){
    var deferred = new $.Deferred();
    console.log("first running")
    return deferred.promise();
}

second = function(){
    console.log("second running..sigh..");
}

$(document).ready(function() {

    first().then(second);

});

Second is not being called.

Upvotes: 0

Views: 941

Answers (2)

Hitmands
Hitmands

Reputation: 14199

You can think a Promise as a task that, in future, will be processed and a result will be returned to all functions that follow the deferred object.

Promises can have 3 + 1 states:

  1. Pending (The task isn't processed yet)
  2. FullFilled or Resolved (Correctly Processed)
  3. Rejected (Processed but failed)
  4. Settled (indicates that the task is already processed.)

var doSomethingAsync = new Promise(function(resolve, reject) {
  window.setTimeout(function() {
    resolve('Hello World');

    // OR
    
    // reject('You Are Not Welcome')
  }, 5000);
});

doSomethingAsync.then(
  function(message) {
    console.log('After few seconds we can finally tell you:', message)
  },
  function(error) {
    console.log('After few seconds we can finally tell you that: ', error);
  }
);

As you can see in the above snippet the then method of a Promise Object accepts TWO params (note, when available, there is a third parameter called notify or progress), the first is called in case of fullfilment, the second in case of rejection.

While the promise is in Pending no callbacks are called!

Upvotes: 1

sma
sma

Reputation: 9597

In order for the second function to be called, you need to resolve the deferred returned from the first function:

first = function(){
    var deferred = new $.Deferred();
    console.log("first running");
    deferred.resolve();  // <----------resolve the deferred
    return deferred.promise();
}

You can also resolve it with arguments so that whatever its resolved with, will be passed as arguments to your second function. Here's a fiddle that adds a slight delay to the resolve so it mimics asynchronous behavior and resolves with actual data:

http://jsfiddle.net/1k6tLev8/1/

Upvotes: 5

Related Questions