Andrey
Andrey

Reputation: 750

How do I chain deferred objects in jQuery?

Just a small piece of code:

return $.when(
  $.get('/url1.json').done(function(r){
    //case 1
  }), $.get('/url2.json').done(function(r) {
    //case 2
  })
).done(function(){return $.get('/url3.json').done(function(r){
  //case 3
})})

What this code does:

  1. Runs gets for /url1.json and /url2.json simultainiously and in case of success runs code for case 1 and case 2 respectively
  2. In case of success of both /usr1.json and url2.json it runs get for /url3.json
  3. Returns deferred object (or a promise, nevermind now as I see) which $.when returns (so, the object for /url1.json and /url2.json by $.when's rules)

What I need from it:
1. ...
2. ...
3. Returns deferred object which is returned by $.get('/url3.json')

So, maybe I need something like

$.when(...).flatMap(function() { return $.get('/url3.json') })

Do I have any way of doing it?

Upvotes: 0

Views: 308

Answers (1)

Jason Harwig
Jason Harwig

Reputation: 45551

Just call then instead of done to change the promise to the result of the passed in callback.

return $.when(
    $.get('/url1.json'), 
    $.get('/url2.json')
  )
  .then(function() {
    return $.get('/url3.json')
  });

http://jsfiddle.net/5N9JJ/3/

Upvotes: 4

Related Questions