SOURCE

var result=[];
for(let i=0;i<10;i++){
    result.push(function(){
        return new Promise((resolve,reject)=>{
            console.log("index:"+i+new Date().toLocaleString())
            setTimeout(() => {
                resolve(i);
                console.log("结束" + i, new Date().toLocaleString());
            }, parseInt(Math.random() * 10000));

        })
        }
    )
}


function PromiseLimit(funcArray, limit = 5) {
  let i = 0;
  const result = [];
  const executing = [];
  const queue = function() {
    if (i === funcArray.length) return Promise.all(executing);
    const p = funcArray[i++]();
    result.push(p);
    const e = p.then(() => executing.splice(executing.indexOf(e), 1));
    executing.push(e);
    if (executing.length >= limit) {
      return Promise.race(executing).then(
        () => queue(),
        e => Promise.reject(e)
      );
    }
    return Promise.resolve().then(() => queue());
  };
  return queue().then(() => Promise.all(result));
}

var a=PromiseLimit(result,3);
console.log(a);
console 命令行工具 X clear

                    
>
console