Created
August 22, 2015 17:28
-
-
Save karenpeng/65e055b47afa215d4d5c 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
function parallel(arrOfFunc, maxNum, callback){ | |
var len = arrOfFunc.length | |
var result = [] | |
// 最好是增加一个标记 | |
var done = false | |
var lastIndex = maxNum -1 | |
for(var i = 0; i < maxNum; i++){ | |
// wrap 为什么要返回一个函数然后执行?直接在 wrap 里面执行就可以了 | |
wrap(i, arrOfFunc[i]) | |
} | |
function wrap(i, func){ | |
func(function(err, value){ | |
if (done) return | |
if(err) { | |
done = true | |
return callback(err) | |
} | |
result[i] = value | |
// 这个检查有点不必要,不如用一个 count 来计数 | |
if(lastIndex === len - 1){ | |
done = true | |
return callback(null, result) | |
} | |
if(lastIndex < len - 1){ | |
lastIndex++ | |
wrap(lastIndex, arrOfFunc[lastIndex]) | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment