Running max N Promises simultaneously with error handling
node.js

Running max N Promises simultaneously with error handling

Marcell Simon
Marcell Simon

If you want to run multiple promises, with Promise.all it will stop at the first error. This little script not just handles errors, but also limits the simultaneous process count.

import pLimit from "p-limit"

const func = async () => {
  const limit = pLimit(2)
  const input = []
  for (let i = 0; i < 5; i++) {
    input.push(limit(() => new Promise(res => res())))
  }
  input.push(limit(() => new Promise((res, rej) => rej(new Error("2")))))

  const results = await Promise.all(input.map(p => p.catch(e => e)))
  for (const result of results) {
    console.log(result instanceof Error)
  }
}

func()


Join the conversation.