Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to synch JavaScript callbacks?
    primarykey
    data
    text
    <p>I've been developing in JavaScript for quite some time but net yet a cowboy developer, as one of the many things that always haunts me is synching JavaScript's callbacks.</p> <p>I will describe a generic scenario when this concern will be raised: I have a bunch of operations to perform multiple times by a for loop, and each of the operations has a callback. After the for loop, I need to perform another operation but this operation can only execute successfully if all the callbacks from the for loop are done. </p> <p><strong>Code Example:</strong></p> <blockquote> <pre><code>for ... in ... { myFunc1(callback); // callbacks are executed asynchly } myFunc2(); // can only execute properly if all the myFunc1 callbacks are done </code></pre> </blockquote> <p><strong>Suggested Solution:</strong></p> <p>Initiate a counter at the beginning of the loop holding the length of the loop, and each callback decrements that counter. When the counter hits 0, execute myFunc2. This is essentially to let the callbacks know if it's the last callback in sequence and if it is, call myFunc2 when it's done.</p> <p><strong>Problems:</strong></p> <ol> <li>A counter is needed for every such sequence in your code, and having meaningless counters everywhere is not a good practice.</li> <li>If you recall how thread conflicts in classical synchronization problem, when multiple threads are all calling var-- on the same var, undesirable outcomes would occur. Does the same happen in JavaScript?</li> </ol> <p><strong>Ultimate Question:</strong></p> <p>Is there a better solution?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload