[JS] Async Queue Problem
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
let queue = []; | |
let running = false; | |
function start(id) { | |
queue.push(id); | |
if (running) return; | |
next(); | |
} | |
function next() { | |
running = true; | |
execute(queue.shift()) | |
.catch(console.error) | |
.then(() => { | |
running = false; | |
if (queue.length) { | |
next(); | |
} | |
}); | |
} | |
console.log('输出结果:'); | |
for (let i = 0; i < 5; i++) { | |
start(i); | |
} | |
function sleep(duration) { | |
return new Promise(resolve => setTimeout(resolve, duration)); | |
} | |
function execute(id) { | |
let duration = Math.floor(Math.random() * 500); | |
return sleep(duration).then(() => { | |
console.log('id', id); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
修改下面的 start 函数, 使 execute 对应的 id 按顺序打印.