Limit Promise Concurrency with pool

By  on  

Methods like Promise.all, Promise.allSettled, Promise.race, and the rest are really excellent for managing multiple Promises, allowing for our apps to embrace async and performance. There are times, however, that limiting the number of concurrent operations may be useful, like rate limiting or simply not wanting to put a server under massive stress.

Enter an simple utility for limiting Promise concurrency: pool!

import pool from '@ricokahler/pool';

async function getQuotes() {
  const quotes = await pool({
    collection: [1, 2, 3, 4, 5],
    maxConcurrency: 2, // Limit 2 requests at a time
    task: async (symbol) => {
      const response = await fetch(`/quotes/${symbol}`);
      const json = await response.json();
      return json;
    },
  });

  console.log(quotes); // Array of the 5 quotes
}

pool lets you specify how many requests to run concurrently. If no concurrency value is provided, pool acts like Promise.all.

Concurrency is an important issue with JavaScript's async nature, so having a method for pooling them together and limiting concurrent actions is important.

Recent Features

  • By
    fetch API

    One of the worst kept secrets about AJAX on the web is that the underlying API for it, XMLHttpRequest, wasn't really made for what we've been using it for.  We've done well to create elegant APIs around XHR but we know we can do better.  Our effort to...

  • By
    Camera and Video Control with HTML5

    Client-side APIs on mobile and desktop devices are quickly providing the same APIs.  Of course our mobile devices got access to some of these APIs first, but those APIs are slowly making their way to the desktop.  One of those APIs is the getUserMedia API...

Incredible Demos

  • By
    MooTools onLoad SmoothScrolling

    SmoothScroll is a fantastic MooTools plugin but smooth scrolling only occurs when the anchor is on the same page. Making SmoothScroll work across pages is as easy as a few extra line of MooTools and a querystring variable. The MooTools / PHP Of course, this is a...

  • By
    Create a Twitter AJAX Button with MooTools, jQuery, or Dojo

    There's nothing like a subtle, slick website widget that effectively uses CSS and JavaScript to enhance the user experience.  Of course widgets like that take many hours to perfect, but it doesn't take long for that effort to be rewarded with above-average user retention and...

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!