JavaScript之手写控制并发请求与图片压缩

78 阅读1分钟

控制并发请求

class TaskQueue{

    constructor(maxConcurrent){
        this.maxConcurrent = maxConcurrent
        this.currentRunning = 0
        this.queue = []
    }

    addQueue(url){
        return new Promise((resolve,reject) => {
            const task = () => {
                this.currentRunning++
                sendMessage().then(resolve).catch(reject).finally(()=>{
                    this.currentRunning--
                    this.deQueue()
                })
            }
            this.queue.push(task)
            this.deQueue()
        })
    }

    deQueue(){
        if (this.currentRunning < this.maxConcurrent && this.queue.length) {
            const task = this.queue.shift()
            task()
        }
    }
}
function concurrentRequest(urls, maxNum) {
    if (urls.length === 0) {
        return Promise.resolve([])
    }

    return new Promise(resolve => {
        let index = 0
        let result = []
        let count = 0
        async function runTask(){
            let url = urls[index]
            const targetIndex = index
            index++
            try {
                const res = await fetch(url)
                result[targetIndex] = res
            } catch (error) {
                result[targetIndex] = error
            } finally {
                count++
                if(count === urls.length){
                    resolve(result)
                }
                if(index < urls.length){
                    runTask()
                }
            }
        }
        for (let i = 0; i < Math.min(urls.length, maxNum); i++) {
            runTask()   
        }

    })
}

图片压缩

class CompressImg{
    constructor(options){
        this.options = options
        this.createBase64()
    }

    createBase64(){
        const reader = new FileReader()
        reader.onload = (e) => {
            const url = e.target?.result
            this.compress(url)
        }
        reader.readAsDataURL(this.options.file)
    }

    compress(str){
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')
        const img = new Image()
        img.src = str
        img.onload = (e) =>{
            canvas.width = img.width
            canvas.height = img.height
            ctx.drawImage(img,0,0,img.height,img.width)
            const base = canvas.toDataURL(this.options.file.type,1)
            this.options.callback(base)
        }
    }
}