Elvis D'Souza
Elvis D'Souza

Reputation: 2313

Replace an older promise with a newer one in a jquery deferred chain

I have an object that uses jQuery's Deferred to create my own promise that I resolve after a timeout. I then chain an ajax call, and return the promise.

var Obj = function() {
  var _obj = new $.Deferred();

  setTimeout(function() {
      _obj.resolve("Resolve One!");
  }, 2000);

  return _obj.promise();
}

new Obj()
.done(function(message) {
  document.write(message);
  return $.get("http://www.jsonip.com/");
})
.done(function(response) {
  document.write(response);
})

I'd expect message to have "Resolve One!" and response to have the response from the ajax call

Result expected:

Resolve One!{"ip":"256.256.0.0","about":"/about"}

What I get instead:

Resolve One!Resolve One!

Since I'm returning $.get(), which is a promise, I'd expect the old promise to be overridden with the one from jQuery. What should I be doing instead, to get the the web page contents into response`?

jsfiddle: http://jsfiddle.net/7zUKg/

Upvotes: 0

Views: 515

Answers (1)

pimvdb
pimvdb

Reputation: 154828

.done only adds the handler. You want .then, which also allows you to return a new promise: http://jsfiddle.net/7zUKg/1/.

new Obj()
.then(function(message) {
  document.write(message);
  return $.get("http://www.jsonip.com/");
})
.done(function(response) {
  document.write(response);
})

Upvotes: 1

Related Questions