编辑代码

let handleList = [] //请求列表
 
/*
 *请求相关处理
 *@params url
 *@params requestObj  请求参数
 *@return {Promise} 请求的promise
 */
function request(url,requestObj={}){
    const sameHandle = handleList.find(
    (item) => item.url === url && JSON.stringify(item.requestObj) === JSON.stringify(requestObj)
  )
  if (sameHandle) {
    // 遇到相同请求直接返回之前请求的promise
    console.log(`存在重复请求,直接返回`)
    return sameHandle.handle
  }
  const handle = new Promise((resolve, reject) => {
    Promise.resolve()
      .then((res) => {
          console.log('请求中----')
          setTimeout(()=>{
               resolve('res====')
          },2000)
       
      })
      .catch((err) => {
        reject(err)
      })
      .finally(() => {
            // 无论请求结果如果,都需要把对应的请求移除掉
             handleList = handleList.filter(
              (item) =>
                item.url !== url && JSON.stringify(item.requestObj) !== JSON.stringify(requestObj)
            )
      })
  })
  handleList.push({ url, requestObj, handle })
  return handle
}

let res1 = request('common').then(res=>{
    console.log(1111,res);
});
let res2 = request('common').then(res=>{
    console.log(2222,res);
});
let res3 = request('common').then(res=>{
    console.log(3333,res);
});

setTimeout(()=>{
    let res1 = request('common').then(res=>{
        console.log(1111,res);
    });
    let res2 = request('common').then(res=>{
        console.log(2222,res);
    });
    let res3 = request('common').then(res=>{
        console.log(3333,res);
    });
},3000)