美文网首页
使用promise实现并发控制

使用promise实现并发控制

作者: holidayPenguin | 来源:发表于2021-06-11 17:44 被阅读0次

原文 https://www.jianshu.com/p/c0644d0262fa

针对原文修改了两个方面:

  • 使用 async await来增强理解
    原文多重then回调理解需要时间
  • 返回了所有请求的返回值
    不论是resolve还是reject
async function limitLoad(urls, handler, limit) {
    const sequence = [].concat(urls)
    let promise = []
    const promiseAll = []
    promise = sequence.splice(0, limit).map((url, index) => {
        const _t = handler(url)
        promiseAll.push(_t)
        return _t.then((res)=>{
            return [index, res]
        })
    })
    for (const item of sequence) {
        const [index] = await Promise.race(promise)
        const _t = handler(item)
        promiseAll.push(_t)
        promise[index] = _t.then((res)=>{
            return [index, res]
        })
    }

    return Promise.allSettled(promiseAll)
}

const urls =[
    {info:'1', time:2000},
    {info:'2', time:1000},
    {info:'3', time:2000},
    {info:'4', time:2000},
    {info:'5', time:3000},
    {info:'6', time:1000},
    {info:'7', time:2000},
    {info:'8', time:2000},
    {info:'9', time:3000},
    {info:'10', time:1000}
]

function loadImg(url){
    return new Promise((reslove, reject)=>{
        console.log(url.info + '---start')
        setTimeout(()=>{
            console.log(url.info, 'ok!!!')
            reslove(url)
        }, url.time)
    })
}

limitLoad(urls, loadImg, 3).then(res => console.log(res))

相关文章

网友评论

      本文标题:使用promise实现并发控制

      本文链接:https://www.haomeiwen.com/subject/llyveltx.html