11
I have a jQuery script that starts two or more asynchronous operations at the same time, and would like to run a callback when all they have been completed. An example would be to start an animation to hide the current page, while making an Ajax request to load the contents of the next page. Both the animation can finish first, and the request. After both are finished, I would like to display the new page.
I would not like the new page to be displayed before the previous one was totally hidden, even if it were before your content is ready. So that the final callback should not be in either one or another event.
How to do? Preferably, I’m looking for a generic solution that works with two or more simultaneous asynchronous events (it’s rare, but could for example have to make more than one simultaneous Ajax request, and just run the callback after having all the results).
Note: I asked the question for Javascript, in general, but a specific solution for jQuery (for example, something involving Deferreds or Promises) would also be of good size.
Great answer, actually I had already read about the
whenbut I didn’t remember him. And that’s calling thepromiseon the return ofhideis news to me, I thought it would be an obstacle to usePromisebut I see it’s not. +1 and I accept!– mgibsonbr