0

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/

Elvis D'Souza
  • 2,273
  • 1
  • 23
  • 31

1 Answers1

1

.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);
})
pimvdb
  • 151,816
  • 78
  • 307
  • 352
  • I'm sure this answer is correct, but you should also put brackets round `(new Obj())`, otherwise `new` will try to apply itself to whatever is returned by the right hand end of the method chain. The "member" operator `.` has higher precedence than `new`, so the entire method chain will execute first. Due to the nature of `Obj()`, (a) lack of brackets may not be an issue in this case, and (b) `new` can be omitted. – Beetroot-Beetroot Feb 01 '13 at 18:25
  • @Beetroot-Beetroot: I'm not sure if that's correct. `new A.b()` requires brackets but `new A().b()` does not. The `new` has higher precedence in that case. – pimvdb Feb 01 '13 at 21:42