Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. 'use strict';
  2. const Queue = require('yocto-queue');
  3. const pLimit = concurrency => {
  4. if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) {
  5. throw new TypeError('Expected `concurrency` to be a number from 1 and up');
  6. }
  7. const queue = new Queue();
  8. let activeCount = 0;
  9. const next = () => {
  10. activeCount--;
  11. if (queue.size > 0) {
  12. queue.dequeue()();
  13. }
  14. };
  15. const run = async (fn, resolve, ...args) => {
  16. activeCount++;
  17. const result = (async () => fn(...args))();
  18. resolve(result);
  19. try {
  20. await result;
  21. } catch {}
  22. next();
  23. };
  24. const enqueue = (fn, resolve, ...args) => {
  25. queue.enqueue(run.bind(null, fn, resolve, ...args));
  26. (async () => {
  27. // This function needs to wait until the next microtask before comparing
  28. // `activeCount` to `concurrency`, because `activeCount` is updated asynchronously
  29. // when the run function is dequeued and called. The comparison in the if-statement
  30. // needs to happen asynchronously as well to get an up-to-date value for `activeCount`.
  31. await Promise.resolve();
  32. if (activeCount < concurrency && queue.size > 0) {
  33. queue.dequeue()();
  34. }
  35. })();
  36. };
  37. const generator = (fn, ...args) => new Promise(resolve => {
  38. enqueue(fn, resolve, ...args);
  39. });
  40. Object.defineProperties(generator, {
  41. activeCount: {
  42. get: () => activeCount
  43. },
  44. pendingCount: {
  45. get: () => queue.size
  46. },
  47. clearQueue: {
  48. value: () => {
  49. queue.clear();
  50. }
  51. }
  52. });
  53. return generator;
  54. };
  55. module.exports = pLimit;