nanha
11/15/2011 - 3:12 AM

async programming: parallel 패턴...

async programming: parallel 패턴...

/**
 * parallel execute
 * 결과

1321326610687
1321326610687
1321326610687
[1, 2, 3]
async
-------------------------------
1321326610688
1321326610688
1321326610688
sync
[1, 2, 3]
*/

var parallel = function parallel(actions) {
  if (!(actions instanceof Array)) {
    actions = Array.prototype.slice.call(arguments);
    var direct = true;
  }
  return function(callback, errback) {
    var results = [],
        counter = actions.length;
    actions.forEach(function (action, i) {
      action(function (result) {
        results[i] = result;
        counter--;
        if (counter <= 0) {
          if (direct) {
            callback.apply(null, results);
          } else {
            callback.call(null, results);
          }
        }
      }, errback);
    });
  }
};
var foo   = function(callback) {
	if( typeof console != 'undefined' ) console.log(+new Date());
	callback(1);
};
var foo2   = function(callback) {
	if( typeof console != 'undefined' ) console.log(+new Date());
	callback(2);
};
var foo3   = function(callback) {
	if( typeof console != 'undefined' ) console.log(+new Date());
	callback(3);
};
parallel(
	foo, foo2, foo3
)(function() {
	if( typeof console != 'undefined' ) console.log(arguments);
});
if( typeof console != 'undefined' ) console.log('async');
console.log('-------------------------------');
var foo   = function(callback) {
	if( typeof console != 'undefined' ) console.log(+new Date());
	return 1;
};
var foo2   = function(callback) {
	if( typeof console != 'undefined' ) console.log(+new Date());
	return 2;
};
var foo3   = function(callback) {
	if( typeof console != 'undefined' ) console.log(+new Date());
	return 3;
};

var p = [];
p.push(foo());
p.push(foo2());
p.push(foo3());
if( typeof console != 'undefined' ) console.log('sync');
if( typeof console != 'undefined' ) console.log(p);