Iwen's blog Iwen's blog
首页
  • 前端文章

    • JavaScript
    • Vue
  • 学习笔记

    • 《JavaScript教程》笔记
    • 《JavaScript高级程序设计》笔记
    • 《ES6 教程》笔记
    • 《Vue》笔记
    • 《TypeScript 从零实现 axios》
    • 小程序笔记
  • HTML
  • CSS
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • Linux
  • 学习
  • 面试
  • 心情杂货
  • 友情链接
  • 网站
  • 资源
  • Vue资源
  • 分类
  • 标签
  • 归档
复盘
关于

Iwen

不摸鱼的哥哥
首页
  • 前端文章

    • JavaScript
    • Vue
  • 学习笔记

    • 《JavaScript教程》笔记
    • 《JavaScript高级程序设计》笔记
    • 《ES6 教程》笔记
    • 《Vue》笔记
    • 《TypeScript 从零实现 axios》
    • 小程序笔记
  • HTML
  • CSS
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • Linux
  • 学习
  • 面试
  • 心情杂货
  • 友情链接
  • 网站
  • 资源
  • Vue资源
  • 分类
  • 标签
  • 归档
复盘
关于
  • Vue

  • Vue进阶

  • CSS

  • ES6

  • Base

  • Core

  • Array

  • Object

  • String

  • Async

  • Browser

  • Http

  • 性能优化

  • 正则

  • 经典总结

  • 设计模式

  • 数据结构

  • 算法

  • 手写

    • call、apply
    • 实现bind函数
    • instanceOf
    • new 原理及模拟实现
    • 防抖、节流
    • 发布订阅模式
    • 深拷贝
    • Promise A+
    • Promise 进阶
    • Array-prototype-map
    • Array-prototype-filter
    • Array-prototype-reduce
    • 并发请求
    • 继承
    • JSON 字符串
  • TypeScript

  • 复盘
  • 手写
Mr.w
2020-11-29

并发请求

# 并发请求

一道常见的面试题

请实现如下的函数,可以批量请求数据,所有的URL地址在urls参数中,同时可以通过max参数,控制请求的并发度。当所有的请求结束后,需要执行callback回调。发请求的函数可以直接使用fetch。

function sendRequest (urls: string[], max: number, callback: () => void) {}
1

fetch 函数返回的是一个promise,promise对象在实例化的时候就已经开始执行了。

const urls = [
    'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2580986389,1527418707&fm=27&gp=0.jpg',
    'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1995874357,4132437942&fm=27&gp=0.jpg',
    'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2640393967,721831803&fm=27&gp=0.jpg',
    'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1548525155,1032715394&fm=27&gp=0.jpg',
    'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2434600655,2612296260&fm=27&gp=0.jpg',
    'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=2160840192,133594931&fm=27&gp=0.jpg'
]

function sendRequest (urls, max, callback) {
    const len = urls.length;                // 请求总数
    let currentIdx = Math.min(max, len);    // 并行限制数
    let counter = 0;                        // 已完成请求数

    function _done() {
        counter++
        if (len === counter) {              // 请求结束,执行回调
            return callback()
        }
        if (currentIdx < len) {             // 进入下一个请求 
            _fetch(urls[currentIdx++])
        }
    }
    function _fetch(url) {
        fetch(url).finally(() => {
            _done()
        })
    }
    for (let i = 0; i < currentIdx; i++) {  // 默认执行请求
        _fetch(urls[i])
    }
}

sendRequest(urls, 2, () => {
    console.log('请求回调')
})

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

另一种方法,队列清空

有时候会同时发起成千上百的请求,为了缓解压力和性能问题,就需要进行请求限制了,也就是要保证每次只能发起 限定的请求数量

class Scheduler {
    constructor() {
        this.queue = [];
        this.maxLimit = 2;
        this.runCounts = 0;
    }
    add(promiseCreator) {
        this.queue.push(promiseCreator)
    }
    taskStart() {
        for (let i = 0; i < this.maxLimit; i++) {
            this.request()
        }
    }
    request() {
        // 保证每次限定请求数量 & 处理边界
        if (!this.queue || !this.queue.length || this.runCounts >= this.maxLimit) {
            console.log('当前执行数量:', this.runCounts)
            return
        }
        this.runCounts++
        /**
         * 取出请求队首的resolve并执行
         * 执行结束后,重新执行此方法
         */
        this.queue.shift()().then(() => {
            this.runCounts--
            this.request()
        })
        console.log('当前执行数量:', this.runCounts)
    }
}

const scheduler = new Scheduler()

// 使用计时器模拟请求速度
const timeout = (time) => new Promise(resolve => setTimeout(resolve, time))

const addTask = (time, value) => {
    scheduler.add(() => timeout(time).then(() => console.log(value)))
}

addTask(1000, '1');
addTask(500, '2');
addTask(300, '3');
addTask(400, '4');
addTask(3000, '5');
addTask(2000, '6');
addTask(2000, '7');
addTask(1000, '8');
addTask(800, '9');
addTask(1000, '10');

scheduler.taskStart()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
Array-prototype-reduce
继承

← Array-prototype-reduce 继承→

最近更新
01
flex布局页面自适应滚动条问题
12-28
02
前后端分离开发请求接口跨域如何携带cookie的问题
12-28
03
怎么实现div长宽比固定width-height4比3
12-28
更多文章>
Theme by Vdoing | Copyright © 2017-2022 Iwen | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式