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
    Send Text Messages with PHP

    Kids these days, I tell ya.  All they care about is the technology.  The video games.  The bottled water.  Oh, and the texting, always the texting.  Back in my day, all we had was...OK, I had all of these things too.  But I still don't get...

  • By
    Animated 3D Flipping Menu with CSS

    CSS animations aren't just for basic fades or sliding elements anymore -- CSS animations are capable of much more.  I've showed you how you can create an exploding logo (applied with JavaScript, but all animation is CSS), an animated Photo Stack, a sweet...

Incredible Demos

  • By
    CSS Counters

    Counters.  They were a staple of the Geocities / early web scene that many of us "older" developers grew up with;  a feature then, the butt of web jokes now.  CSS has implemented its own type of counter, one more sane and straight-forward than the ole...

  • By
    CSS Tooltips

    We all know that you can make shapes with CSS and a single HTML element, as I've covered in my CSS Triangles and CSS Circles posts.  Triangles and circles are fairly simply though, so as CSS advances, we need to stretch the boundaries...

Discussion

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