I am looking for a way to call a function only after .each()
finishes its execution. In the example below, how to make sure that postPreparation()
runs immediately after $('.element').each()
completes?
$('.element').each(function() {
/**
* 'prepareLayer()' is a complex function that takes a while to complete and,
* as in this construct, needs to be invoked for each matched element. Basically,
* 'prepareLayer()' adds a lot of new HTML elements to the page.
*/
prepareLayer();
});
/**
* Ideally, this should immediately run _after_ the above function completes
* i.e. after each '.element' finishes running prepareLayer().
*
* 'postPreparation()' needs to attach some event handlers for the new HTML elements
* created in 'prepareLayer()'.
*/
postPreparation();
Technically, I am looking for a way to invoke a callback function for .each()
.
NOTE: I just confirmed, in the example above, that postPreparation()
will execute only after .each()
completes. The problem was my prepareLayer()
builds the new HTML elements using AJAX, so each()
returns prematurly. As suggested by @Alnitak, an asynchronous AJAX request wouldn't stop .each()
from returning prematurely.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…