0

Say I have a list of items like so:

const list = [0, 1, 2, 3, 4];

and I have some async fetch function:

async function fetchSomething(x) { /* ... */ }

I was wondering if there was a way to map the list to the result of fetchSomething but *have each fetch run after the next.

I know I can do this with async and await using for ... of loops like so:

const list = [0, 1, 2, 3, 4];

function fetchSomething(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      const value = `fetched ${x}!`;
      console.log(value);
      resolve(value);
    }, 500);
  });
}

async function main() {
  const newList = [];

  for (const item in list) {
    newList.push(await fetchSomething(item));
  }

  console.log({newList});
}

main();

but that isn't very "functional".

I also know I could use Promise.all but the issue is that it fires off all the promises at once. I'd prefer if they went off sequentially:

const list = [0, 1, 2, 3, 4];

function fetchSomething(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      const value = `fetched ${x}!`;
      console.log(value);
      resolve(value);
    }, 500);
  });
}

async function main() {
  const newList = await Promise.all(list.map(x => fetchSomething(x)));
  console.log({newList});
}

main();

Any idea of how to map a list of items to promises and have each promise complete sequentially and still have it be "functional"/declarative style?

Rico Kahler
  • 17,616
  • 11
  • 59
  • 85
  • Writing code with sideeffects like timeouts and network requests isn't very functional anyway, so I would recommend to just use `await` in a loop. – Bergi Feb 07 '18 at 17:00
  • @Bergi I came up with [this](https://gist.github.com/ricokahler/969e9021c28fc862fd2532f96b02ffa0) – Rico Kahler Feb 07 '18 at 17:03
  • Sure, you can always wrap locally mutating code in a functional abstraction :-) – Bergi Feb 07 '18 at 17:12
  • To change an array of numbers to a single promise that sequentially executes functions that return a promise with the values you can use `reduce` or `recursion` an example can be found [here](https://jsfiddle.net/o2rv517g/) – HMR Feb 08 '18 at 03:50

0 Answers0