Created
November 15, 2011 03:12
-
-
Save nanha/1366025 to your computer and use it in GitHub Desktop.
async programming: parallel 패턴...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment