Skip to content

Instantly share code, notes, and snippets.

@mctep
Created April 17, 2014 14:25
Show Gist options
  • Save mctep/10987531 to your computer and use it in GitHub Desktop.
Save mctep/10987531 to your computer and use it in GitHub Desktop.
Параллельное и последовательное выполнения асинхронного кода
function initA(cb) {
setTimeout(function() {
var a = 1;
cb(a);
}, Math.random() * 3000);
}
function initB(cb) {
setTimeout(function() {
var b = 2;
cb(b);
}, Math.random() * 3000);
}
function initC(cb) {
setTimeout(function() {
var c = 3;
cb(c);
}, Math.random() * 3000);
}
function paralell(arr, cb) {
var length = arr.length;
var count = 0;
var results = [];
arr.forEach(function(fn, i) {
fn(function(x) {
results[i] = x;
count++;
if (count == length) {
cb(results)
}
});
});
}
function linear(arr, cb) {
var results = [];
function foo(arr, index) {
arr[index](function(x) {
results[index] = x;
index++;
if (index < arr.length) {
foo(arr, index);
} else {
console.log(results)
cb(results);
}
});
}
foo(arr, 0);
}
linear([
function(cb) {
initA(cb);
},
function(cb) {
initB(cb);
},
function(cb) {
initC(cb);
}
], function(args) {
var a = args[0];
var b = args[1];
var c = args[2];
foo(a,b,c);
});
function foo(a, b, c) { console.log(a + b + c); }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment