面试题-封装并发数量可控的函数

169 阅读1分钟
const urlList:string[]=[];
const maxNum=2
for (let index = 0; index < 10; index++) {
    urlList.push('https://jsonplaceholder.typicode.com/todos/'+index)
}
//书写这个 concurrent方法 ,并把结果一一对应返回数组结果
concurrent(urlList,maxNum).then(result=>{
    console.log(result)
})

jsonplaceholder.typicode.com 是个接口测试网站 答案如下

interface Result{
    [propName: string]:any
}
export const concurrent=(urlList:string[],maxNum:number)=>{
    return new Promise((resolve)=>{
        const resultList:Result=[]
        let index=0
        async function requestFn(){
            const i=index
            index++
            try {
                const resp=await fetch(urlList[i]).then(resp=>resp.json())
                resultList[i]=resp
            } catch (error) {
                resultList[i]=error
            }finally{
                if(index<urlList.length){
                    requestFn()
                }else{
                    resolve(resultList)
                }
            }
        }
        
        //发送请求
        const min=Math.min(maxNum,urlList.length)
        for (let index = 0; index < min; index++) {
            requestFn()
        }
        

    })
}