1

I am trying to implement parallel(funcList, done) to implement the call to each of the functions passed at the same time.

    parallel([
    function(cb) { setTimeout(1000, cb); },
    function(cb) { setTimeout(2000, cb); },
    function(cb) { $.get('example.com').always(cb); }
],
function() { alert('done'); }

);

Any pointers would be a great help..

8
  • so is cb the final callBack? or is that supposed to be some other function? What exactly do you want to happen? Might need some more info. Commented Aug 6, 2015 at 0:13
  • 1
    You can't really reliably have true simultaneous execution, at least not in browser environments. Concurrency is event-driven in the JavaScript runtime. The closest approximation you could have here is to have all your function inputs in parallel() executed with setTimeout(f, 0) – your functions won't truly run simultaneously, but they will at least run independently and the parallel() function will return immediately to the caller. What is it you're really trying to achieve here? Commented Aug 6, 2015 at 0:14
  • I have this which probably is close to what you are suggesting David: var parallel = function(fcnList, done) { var i = 0; for (i = fcnList.length(); i>0; i--) { (function(arg) { setTimeout(function() { var fun = fcnList.pop(); fun(); }, 0); }( (i); done(); }; Commented Aug 6, 2015 at 0:51
  • James, assuming cb is a callback function for each of the function passed in, Commented Aug 6, 2015 at 0:56
  • @DavidPisoni: You perhaps forgot about web workers? Commented Aug 6, 2015 at 2:22

1 Answer 1

1

The async library has a method that does what you are looking to do and is very reliable. https://github.com/caolan/async#parallel

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! I was looking at doing this without using any framework.
@annukath: It's not a framework. It's just a library. And each function in that library is mostly independent of each other so you can probably just copy the parallel function and use it directly in your project (note that you must respect the open-source license). If you're interested in how the functions in the async library work you may want to look at my answer to this old question (posted before the async library was written): stackoverflow.com/questions/4631774/…
Note that if you decide to use my stackoverflow answer instead of the async library, you should respect the stackoverflow license (in some ways simpler than the license async uses): stackoverflow.com/help/licensing
annukath, you're correct, I used the wrong word. Updated the answer, it is a library not a framework.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.