Last active
September 4, 2016 10:49
-
-
Save bramblex/c122b95f23ba0fe6c2ccf0c0808e2455 to your computer and use it in GitHub Desktop.
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
// 定义一个函数 sync 封装一个同步函数静如异步队列。 | |
var sync = function(sync_func){ | |
return function(data, next){ | |
next(sync_func(data)); | |
}; | |
}; | |
// 将一个异步队列组合成一个可以执行的异步函数 | |
var compose = function(async_function_list, callback){ | |
return async_function_list.reduceRight(function(left, right){ | |
return function(data){ | |
right(data, left); | |
}; | |
}, callback); | |
}; | |
// 异步函数队列 | |
var job_list = [ | |
function(data, next){ | |
setTimeout(function(){ | |
next(data + 1); | |
}, 1e3); | |
}, | |
// 用 sync 将同步函数混入异步队列 | |
sync(function(data){ | |
return data + 2; | |
}), | |
function(data, next){ | |
setTimeout(function(){ | |
next(data + 3); | |
}, 1e3); | |
}, | |
]; | |
// 可以非常方便的给异步函数队列加入新的特性,甚至是错误处理也可以这样加入 | |
var job_list_with_process = job_list.map(function(async_job){ | |
return function(data, next){ | |
console.log(data); | |
async_job(data,next); | |
}; | |
}) | |
// 用 compose 函数将异步函数队列串成一个函数,并定义异步队列完成后的 callback | |
var asyncJob = compose(job_list_with_process, function(data){ | |
console.log('done with:', data) | |
}); | |
// 执行 | |
asyncJob(0); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment