Using Y.Parallel
for batch async function calls.
You may need to do a batch of asyncronious function calls and never care that each one is done,
you just care that all of them are done. That's where Y.Parallel
comes in handy.
Y.Parallel
is more like a stack tool than anything else. First you create your stack:
var stack = new Y.Parallel();
Then you can start adding callbacks to that stack:
var stack = new Y.Parallel(); stack.add(function() {}); stack.add(function() {}); stack.add(function() {}); stack.add(function() {});
Finally, you listen for the stack to be complete:
stack.done(function() { Y.log('Stack complete'); });
This is a simple example of calling a callback once all 5 of the Y.later
calls have completed.
YUI().use('parallel', 'node', function(Y) { //Create the stack var stack = new Y.Parallel(), //Setup our results node res = Y.one('#results'); //Listen for the click on the button Y.one('#runner').on('click', function(e) { //Prevent the link from navigating e.preventDefault(); //Note that we are starting the test. res.append('<strong>Running example</strong><br><br>'); for (var i = 1000; i <= 5000; i=i+1000) { //Adding a timeout with callback for ~1s apart. Y.later(i, null, stack.add(function() { //This is called when the timeout is reached. res.append('Callback fired<br>'); })); } //What to do when all the callbacks are completed. stack.done(function() { res.append('<br><strong>All Callbacks Done!</strong>'); }); }); });