Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The good news is that JavaScript is single threaded; this means that solutions will generally work well with "shared" variables, i.e. no mutex locks are required.</p> <p>If you want to serialize asynch tasks, followed by a completion callback you could use this helper function:</p> <pre><code>function serializeTasks(arr, fn, done) { var current = 0; fn(function iterate() { if (++current &lt; arr.length) { fn(iterate, arr[current]); } else { done(); } }, arr[current]); } </code></pre> <p>The first argument is the array of values that needs to be passed in each pass, the second argument is a loop callback (explained below) and the last argument is the completion callback function.</p> <p>This is the loop callback function:</p> <pre><code>function loopFn(nextTask, value) { myFunc1(value, nextTask); } </code></pre> <p>The first argument that's passed is a function that will execute the next task, it's meant to be passed to your asynch function. The second argument is the current entry of your array of values.</p> <p>Let's assume the asynch task looks like this:</p> <pre><code>function myFunc1(value, callback) { console.log(value); callback(); } </code></pre> <p>It prints the value and afterwards it invokes the callback; simple.</p> <p>Then, to set the whole thing in motion:</p> <pre><code>serializeTasks([1,2, 3], loopFn, function() { console.log('done'); }); </code></pre> <p><a href="http://jsbin.com/elebok/1/"><strong>Demo</strong></a></p> <p>To parallelize them, you need a different function:</p> <pre><code>function parallelizeTasks(arr, fn, done) { var total = arr.length, doneTask = function() { if (--total === 0) { done(); } }; arr.forEach(function(value) { fn(doneTask, value); }); } </code></pre> <p>And your loop function will be this (only parameter name changes):</p> <pre><code>function loopFn(doneTask, value) { myFunc1(value, doneTask); } </code></pre> <p><a href="http://jsbin.com/elebok/2/"><strong>Demo</strong></a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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