We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
针对fn1,fn2,fn3,fn4实现一个异步并发队列函数schedule(n),保证以下输出:
fn1
fn2
fn3
fn4
schedule(n)
n = 1
n = 2
n = 3
n >= 4
思路:
实现如下:
const fn1 = ()=>new Promise((resolve)=>{ setTimeout(()=>{ resolve(1) },1000) }) const fn2 = () => new Promise((resolve)=>{ setTimeout(()=>{ resolve(2) },2000) }) const fn3 = () => new Promise((resolve)=>{ setTimeout(()=>{ resolve(3) },3000) }) const fn4 = () => new Promise((resolve)=>{ setTimeout(()=>{ resolve(4) },4000) }) function schedule(max){ const queue = [] const asyncQueue = [] let count = 0 let cur = null function push(fn){ queue.push(fn) } function pop(){ return queue.shift() } function execute(task){ count++ return task().then(res=>{ count-- const cur = asyncQueue.shift() const next = cur?.next const asyncResolve = cur?.resolve if(asyncResolve && next){ next().then(res=>{ asyncResolve(res) }) } return res }) } function next(){ const cur = pop() return execute(cur) } function run(){ return count < max ? next() : new Promise((resolve)=>{ asyncQueue.push({ next: next, resolve }) }) } return { push, run } } const sd = schedule(1) sd.push(fn1) sd.push(fn2) sd.push(fn3) sd.push(fn4) sd.run().then(res=>{ console.log(res, new Date().getSeconds()) }) sd.run().then(res=>{ console.log(res, new Date().getSeconds()) }) sd.run().then(res=>{ console.log(res, new Date().getSeconds()) }) sd.run().then(res=>{ console.log(res, new Date().getSeconds()) })
运行: 当n = 1时,输出结果(1,2,3,4)分别相距 2秒/3秒/4秒:
The text was updated successfully, but these errors were encountered:
No branches or pull requests
针对
fn1
,fn2
,fn3
,fn4
实现一个异步并发队列函数schedule(n)
,保证以下输出:n = 1
时,输出结果(1,2,3,4)分别相距 2秒/3秒/4秒n = 2
时,输出结果(1,2,3,4)分别相距 1秒/2秒/2秒n = 3
时,输出结果(1,2,3,4)分别相距 1秒/1秒/2秒n >= 4
时,输出结果(1,2,3,4)分别相距 1秒/1秒/1秒思路:
实现如下:
运行:
当
n = 1
时,输出结果(1,2,3,4)分别相距 2秒/3秒/4秒:The text was updated successfully, but these errors were encountered: