Skip to content

Instantly share code, notes, and snippets.

@karenpeng
Last active January 12, 2016 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karenpeng/c1cfb3c2c3bd15626edd to your computer and use it in GitHub Desktop.
Save karenpeng/c1cfb3c2c3bd15626edd to your computer and use it in GitHub Desktop.
// 实现一个函数 sequence,参数是一个数组,是一系列的异步函数,返回一个新的函数,
//这个新的函数在调用的时候,会顺序的执行之前传递给 sequence 的函数数组,前一个函数的返回值作为下一个函数的参数,新函数的参数前面部分会传递给函数数组的第一个函数,
//当全部执行完成后,调用 新函数的 callback
sequence([add1, add2])(1, function (err, res) {
if(err) {
console.log(err);
return;
}
console.log(res) // 4
})
function add1(input, callback) {
setTimeout(callback.bind(null, null, input + 1), 1000);
}
function add2(input, callback) {
setTimeout(callback.bind(null, null, input + 2), 1000);
}
function sequence(arr){ //this, arguments
var funcs = Array.prototype.slice.call(arr); // -> arr.slice();
var index = -1;
return function haha(input, cb){
if(!funcs[index + 1]) return cb(undefined, input);
var cur = funcs[++index];
cur(input, function(err, res){
if(err) return cb(err);
//console.log(res);
haha(res, cb);
});
}
}
// 实现一个函数 parallel,第一个参数是一个数组,是一系列的异步函数,第二个参数是一个 callback,执行的时候会并发的执行函数数组,当全部函数执行完的时候调用 callback,参数为之前所有异步函数的结果组成的数组。如果要增加一个参数用来控制并发数,如何重构。
parallel([get.bind(get, 1), get.bind(get, 2), get.bind(get, 3), get.bind(get, 4), get.bind(get, 5)], 3, function (err, res) {
console.log(res) // res 是按顺序的两个异步函数执行的结果
})
function get(input, callback) {
setTimeout(callback.bind(null, null, input), Math.random() * 1000);
}
function parallel(arr, max, cb){
var count = 0;
var result = [];
function haha(index) {
arr[index](function(err, res){
result[index] = res;
++count;
if (count === arr.length) {
cb(null, result);
}
if(count + max - 1< arr.length){
haha(count + max - 1);
}
});
}
for(var i = 0; i < max; ++i){
haha(i);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment