Created
March 2, 2018 09:14
-
-
Save hjkcai/d6222f9efc9a657ee487c2b1434a0903 to your computer and use it in GitHub Desktop.
2018-3-2 面试题(面试结束时的版本)
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(tasks, concurrency),让 tasks 并发执行(并控制并发数为 concurrency) | |
// 其中 tasks 为一个数组,每一个元素都是一个方法返回一个 promise | |
// 当所有 tasks 执行完成时,resolve 一个数组保存所有的结果 | |
// 当任意一个 task 执行失败时,reject 这个错误 | |
const assert = require('assert') | |
function task (input) { | |
return () => new Promise(resolve => { | |
setTimeout(() => resolve(input), 1000) | |
}) | |
} | |
parallel([ | |
task(1), | |
task(2), | |
task(3), | |
task(4), | |
task(5), | |
], 2) | |
.then(res => assert.deepEqual(res, [1, 2, 3, 4, 5])); | |
function parallel (tasks, concurrency) { | |
return new Promise((resolve, reject) => { | |
const result = tasks.slice() | |
let promiseChain = Promise.resolve() | |
let running = 0 | |
let index = 0 | |
function runTask (i) { | |
running++ | |
const taskPromise = tasks[i]() | |
promiseChain = promiseChain.then(() => taskPromise) | |
return taskPromise.then(taskResult => { | |
console.log(taskResult) | |
result[i] = taskResult | |
running-- | |
}) | |
} | |
function scheduleNextTask () { | |
if (running < concurrency) { | |
runTask(index++).then(() => { | |
if (index === tasks.length) { | |
resolve(promiseChain.then(() => result)) | |
} else { | |
scheduleNextTask() | |
} | |
}) | |
} | |
} | |
while (running < concurrency && index < tasks.length) { | |
scheduleNextTask() | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment