中间件-js并发加载函数

/*
并发加载函数
id:唯一值
syncFunc:加载函数
 */
const _map={}
async function conCurentLoad (id,syncFunc) {
  //兼容并发加载的情况
  if(!_map[id]){
    _map[id]=[];
    const res = await syncFunc();
    if(_map[id].length>0){
      _map[id].forEach(function (callback) {
        callback(res)
      })
    }
    delete _map[id]
    return res;
  }else{
    return new Promise(function (resolve) {
      _map[id].push(resolve)
    });
  }
}
//并发加载demo
async function init(){
  const midajax= function(){
    return new Promise(function (resolve,reject) {
      setTimeout(function () {
        resolve(21)
      },3000)
    })
  }
  conCurentLoad(1,midajax).then(function (res) {
    console.log(res)
  })
  conCurentLoad(1,midajax).then(function (res) {
    console.log(res)
  })
}
init()

  

posted @ 2020-11-13 19:20  无工时代  阅读(124)  评论(0编辑  收藏  举报