-
-
Notifications
You must be signed in to change notification settings - Fork 230
New issue
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
实现 如果上一次的没请求完,之后的就无响应 #146
Comments
let runningTask = 0; |
let isRequesting = false function myRequest(url) { isRequesting = true myRequest('https://jsonplaceholder.typicode.com/todos/1') myRequest('https://jsonplaceholder.typicode.com/todos/5') myRequest('https://jsonplaceholder.typicode.com/todos/4') myRequest('https://jsonplaceholder.typicode.com/todos/3') myRequest('https://jsonplaceholder.typicode.com/todos/2') |
function promiseWrapper(fetchApi) { // 测试用例 request().then(() => { request().then(() => { setTimeout(() => { |
是不是考promise的链式执行? |
// 使用调度器实现,控制并发为1
class Scheduler {
constructor (maxTask) {
// 最大并发量
this.maxTask = maxTask
// 任务队列
this.queue = []
// 当前执行任务的数量
this.currentTask = 0
}
// 添加任务
addTask (task) {
return new Promise((resolve, reject) => {
this.queue.push({
task,
resolve,
reject
})
this.runTask()
})
}
// 执行任务
runTask () {
// 未达到最大并发量
while (this.currentTask < this.maxTask && this.queue.length > 0) {
const { task, resolve, reject } = this.queue.shift()
// 当前执行的任务
this.currentTask++
task().then(resolve, reject).finally(() => {
this.currentTask--
this.runTask()
})
}
}
}
// 示例任务函数
function createTask (time) {
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, time);
});
}
// 创建调度器实例,设置并发数为2
const scheduler = new Scheduler(1);
function add (time, name) {
scheduler.addTask(() => createTask(time)).then(() => {
console.log(name)
})
}
add(1000, 1)
add(1000, 2)
add(1000, 3)
|
No description provided.
The text was updated successfully, but these errors were encountered: