p-limit npm包学习

Created by Qiwei on 3/6/2021

今天看到一个面试问题:有200个异步请求,最多同时只能由5个请求发出,怎样才能最快的获取所有数据?

这道题需要对并发的请求数做限制,保证每个时刻有5个正在进行的请求,从这篇博客中了解到用 p-limit、async-pool、es6-promise-pool 这些 npm 包可以实现这个功能。这里学习下 p-limit 的代码,它是 sindresorhus 写的,有四千多万周下载,代码也比较容易理解。

使用方法

const pLimit = require('p-limit');

const limit = pLimit(5);

const input = [
  limit(() => fetchSomething('first req')),
  limit(() => fetchSomething('second req')),
  // ...more
];

(async () => {
  const result = await Promise.all(input);
  console.log(result);
})();

代码

代码来自 p-limit 的 main branch

// yocto-queue 是一个 queue 的实现,它的 dequeue 是 O(1) 的,用 linked list 实现,很容易理解(如果用 Array.shift() 是 O(n)的)
const Queue = require('yocto-queue');

// 从下往上看更容易懂

const pLimit = concurrency => {
  // concurrency 是要限制的最大并发数量
  // 检查是否是正整数
  if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) {
    throw new TypeError('Expected `concurrency` to be a number from 1 and up');
  }

  const queue = new Queue(); // 用来储存任务
  let activeCount = 0; // 在线请求的数量

  // 获取下一个任务并执行
  const next = () => {
    activeCount--;

    if (queue.size > 0) {
      queue.dequeue()(); // queue.dequeue() 返回的是之前放进去的一个 run 函数,这里直接执行
    }
  };

  // 异步执行任务(fn)
  const run = async (fn, resolve, args) => {
    activeCount++;

    const result = (async () => fn(...args))();

    resolve(result);

    try {
      await result;
    } catch {} 

    next(); // 现在完成了一个,可以获取队列中的下一个任务并执行(有点递归的感觉)
  };

  // 放入一个任务到 queue 里面
  // 放入后,如果正在执行的任务数量 < 5,就从队列拿出来一个并执行
  const enqueue = (fn, resolve, args) => {
    queue.enqueue(run.bind(null, fn, resolve, args));

    (async () => {
      // This function needs to wait until the next microtask before comparing
      // `activeCount` to `concurrency`, because `activeCount` is updated asynchronously
      // when the run function is dequeued and called. The comparison in the if-statement
      // needs to happen asynchronously as well to get an up-to-date value for `activeCount`.

      // 上面这段英文注释是本来就有的,解释了为什么 `activeCount` 和 `concurrency` 的比较也在异步执行中
      // 是为了要在下一个微任务阶段才比较 `activeCount` 和 `concurrency` 的大小,
      // 因为 `queue.dequeue()()` 是需要异步执行,过程中 run 函数会更新 `activeCount`,
      // 要确保在比较时 `activeCount` 的值是最新的,所以 if statement 也要等到下一个微任务阶段

      await Promise.resolve();

      if (activeCount < concurrency && queue.size > 0) {
        queue.dequeue()(); // 如果目前没有超过并发限制,开始获取并执行 queue 中的任务
      }
    })();
  };

  const generator = (fn, ...args) => new Promise(resolve => {
    enqueue(fn, resolve, args);
  });

  Object.defineProperties(generator, {
    activeCount: {
      get: () => activeCount
    },
    pendingCount: {
      get: () => queue.size
    },
    clearQueue: {
      value: () => {
        queue.clear();
      }
    }
  });

  return generator;
};

module.exports = pLimit;

回答最上面的面试问题:需要做的是控制 promise 的实例化,promise.all 会直接实例化所有的请求,不能直接用,需要用一个队列,添加(enqueue)时检查有没有超过5个正在处理的请求,没有的话就直接拿出来执行,有的话就暂时放在队列里面;后面等请求完成一个时,就会把队列最前面的拿出来并开始执行。