Multiple Chained promises with jquery when()

Just a quick note – I’d like to write it up properly, but spent enough time fixing this I can’t afford to write a long post – despite the fact it’s those long fixes that most deserve it.

I was trying to chain multiple jquery promises, and it just wasn’t quite working – what I was doing was something like this:

I have three asynchronous functions, but one of them is dependant on the result of another, and when all have completed I need to do something else.

So, I ran a when, with arguments that were functions which called the asynch functions and returned deferred (promise) objects. When the asynchs completed a callback would declare the promises complete.

Seemed to make sense.

Note that these functions are members of an object (not shown)

Well of course it seemed to make sense, based on what I’d seen in the documentation, but it didn’t work.

Eventually based on an approach seen in this SO answer by Niko, I found a working method was to assign deferred objects to variables, and watch those in with(), calling my functions seperately.

Looks a lot clunkier, but it worked:

The odd thing about this pattern is that the ‘action’ of each function comes at the end – a little counterintuitive at first!

Leave a Reply

Your e-mail address will not be published. Required fields are marked *