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
    CSS vs. JS Animation: Which is Faster?

    How is it possible that JavaScript-based animation has secretly always been as fast — or faster — than CSS transitions? And, how is it possible that Adobe and Google consistently release media-rich mobile sites that rival the performance of native apps? This article serves as a point-by-point...

  • By
    5 Ways that CSS and JavaScript Interact That You May Not Know About

    CSS and JavaScript:  the lines seemingly get blurred by each browser release.  They have always done a very different job but in the end they are both front-end technologies so they need do need to work closely.  We have our .js files and our .css, but...

Incredible Demos

  • By
    Reverse Element Order with CSS Flexbox

    CSS is becoming more and more powerful these days, almost to the point where the order of HTML elements output to the page no longer matters from a display standpoint -- CSS lets you do so much that almost any layout, large or small, is possible.  Semantics...

  • By
    MooTools PulseFade Plugin

    I was recently driven to create a MooTools plugin that would take an element and fade it to a min from a max for a given number of times. Here's the result of my Moo-foolery. The MooTools JavaScript Options of the class include: min: (defaults to .5) the...

Discussion

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