Continue execution only after .each () Terminates

I am looking for a way to call a function only after .each() its execution. In the example below, how to make sure that postPreparation() is executed immediately after the completion of $('.element').each() ?

 $('.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 * ie after each '.element' finishes running prepareLayer(). * * 'postPreparation()' needs to attach some event handlers for the new HTML elements * created in 'prepareLayer()'. */ postPreparation(); 

Technically, I'm looking for a way to call a callback function for .each() .

NOTE I just confirmed in the above example that postPreparation() will only execute after .each() . The problem was that my prepareLayer() was creating new HTML elements using AJAX, so each() returning prematurely. As @Alnitak suggested, an asynchronous AJAX request will not stop returning .each() ahead of schedule.

+4
source share
3 answers

Until prepareLayer() , until prepareLayer() does something asynchronous (e.g., AJAX or animation), each loop loop cannot be completed until prepareLayer() until prepareLayer() is complete and your code is already there carry out what you want.

FWIW, if there are no additional operations or parameters in your existing .each loop, you just need to write this:

 $('.element').each(prepareLayer); 

those. there is no need for an additional shell of an anonymous function.

On the other hand, if it does something asynchronous, use deferred objects:

 var def = []; $('.element').each(function() { // have prepareLayer return a _promise_ to return def.push(prepareLayer()); }); function prepareLayer() { var jqxhr = $.get(..., function() { // do stuff with content }); return jqxhr; } // use "when" to call "postPreparation" once every // promise has been resolved $.when.apply($, def).done(postPreparation); 
+9
source

I would postPreperation call in some kind of counter object.

For instance:

 function createEvent(numOfSignals, callback) { var _event = {}; _event.signal = function() { if(numOfSignals > 1) { numOfSignals--; } else { callback(); } }; return _event; } var event = createEvent(numOfPreperations, postPreperation); 

Then inside prepareLayer I would call event.signal() . If numOfSignals is 1, then postPreperation will be called immediately.

You need to clarify this, but the basic idea should work. You can check the example here .

0
source

Use jquery promise:

 $('.element').promise().done(function() { postPreparation(); }); 
0
source

Source: https://habr.com/ru/post/1393484/


All Articles