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
    Designing for Simplicity

    Before we get started, it's worth me spending a brief moment introducing myself to you. My name is Mark (or @integralist if Twitter happens to be your communication tool of choice) and I currently work for BBC News in London England as a principal engineer/tech...

  • By
    6 Things You Didn’t Know About Firefox OS

    Firefox OS is all over the tech news and for good reason:  Mozilla's finally given web developers the platform that they need to create apps the way they've been creating them for years -- with CSS, HTML, and JavaScript.  Firefox OS has been rapidly improving...

Incredible Demos

  • By
    background-size Matters

    It's something that makes all men live in fear, and are often uncertain of. It's never spoken, but the curiosity is always there. Nine out of ten women agree in the affirmative. Advertisers do their best to make us feel inadequate but...

  • By
    Google Extension Effect with CSS or jQuery or MooTools JavaScript

    Both of the two great browser vendors, Google and Mozilla, have Extensions pages that utilize simple but classy animation effects to enhance the page. One of the extensions used by Google is a basic margin-top animation to switch between two panes: a graphic pane...

Discussion

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