一个简单版本的并发队列
发布于 2 个月前 作者 spitWind 600 次浏览 来自 分享

lock-func 包增加了 declare function SimpleQueue<T>(job: () => Promise<T>, maxTime: number, queueNum: number):Promise<T[]> 即在以并发 queueNum 数对 job 执行maxTime 次数; 测试样例见 testQueue.js

/**
 *
 * @param {function():Promise.<any>} job 
 * @param {Number} queueNum  并发数量
 *  @param {Number}  maxTime 执行次数
 */
async function SimpleQueue(job, maxTime, queueNum) {
  var tskList = []; //
  var result=new Array(maxTime);
  async function runAction(tskid, job,index) {
    result[index]=await job();
    return tskid;
  }
  for (let i = 0; i < maxTime; i++) {
    if (i < queueNum) {
      tskList[i] = runAction(i, job,i);
      continue;
    }
    var index = await Promise.race(tskList);
    tskList[index] = runAction(index, job,i);
  }
  await Promise.all(tskList);
  return result;
}

测试样例:::

function later(time, msg) {
  msg && console.log("延时" + time + "," + msg);
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve(time);
    }, time);
  });
}
function test() {
  var jobIndex = 0;
  var runNum = 0;
  var start = new Date().getTime();
  console.log("run start:" + start);
  function job(params) {
    runNum++;
    var k = jobIndex++;
    console.log(
      "任务开始:" +
        k +
        ";从启动过了" +
        (new Date().getTime() - start) +
        ";当前任务数:" +
        runNum
    );
    return later(1000).then(function(params) {
      console.log("任务结束:" + k);
      runNum--;
      return k;
    });
  }
  return job;
}
var job = test();
var SimpleQueue = require("./SimpleQueue").SimpleQueue;
SimpleQueue(job, 100, 10); //执行100次///10个并发

调用 npm install lock-func

require("lock-func/SimpleQueue.js")
1 回复

走过路过留个言???

回到顶部