Skip to content

Instantly share code, notes, and snippets.

@w33ble
Last active September 22, 2022 07:49
Show Gist options
  • Save w33ble/e8c66f5d0c16be26dd9df700ef575ecc to your computer and use it in GitHub Desktop.
Save w33ble/e8c66f5d0c16be26dd9df700ef575ecc to your computer and use it in GitHub Desktop.
native promise mapSeries implementation
function mapSeries(arr) {
if (!Array.isArray(arr)) throw new Error('mapSeries requires an Array');
const length = arr.length;
const results = new Array(length);
arr.reduce((chain, item, i) => {
return chain.then(() => item).then(val => results[i] = val);
}, Promise.resolve())
.then(() => results);
}
@ReeganExE
Copy link

TypeScript version:

function mapSeries<T, R>(
  arr: T[],
  map: (p: T, index: number, arrayLength: number) => R | Promise<R>
): Promise<R[]> {
  if (!Array.isArray(arr)) throw new Error('mapSeries requires an Array');
  const results = new Array<R>(arr.length);

  return arr
    .reduce(
      (chain, item, i, arr) =>
        chain
          .then(() => map(item, i, arr.length))
          .then((val) => {
            results[i] = val;
          }),
      Promise.resolve()
    )
    .then(() => results);
}

Usage

const productIds = ['a', 'b', 'c'];
mapSeries(productIds, (p) =>
  fetch(`/api/product/${p}`).then((r) =>
    r.json()
  )
).then((products) =>
  console.log(products)
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment