DEV Community

loading...

Discussion on: Dealing with Promises In an Array with async/await

Collapse
cortadoj profile image
Cortado-J

Thanks for great post @afif Sohaili.

I'm new to javascript but not new to programming.
I was interested in the "Complete async tasks in sequence" method using reduce as you describe.
In the spirit of "DRY", I immediately wanted to encapsulate it:

    function sequencer(array, waitForThis, andThen){
      return (async function() {
        await array.reduce(async (previousPromise, item) => {
          await previousPromise;
          const result = await waitForThis(item);
          andThen(result)
        }, Promise.resolve());
      })()
    }
Enter fullscreen mode Exit fullscreen mode

which then gives us the re-usable "sequencer" which takes as parameters:

  • An array of values which are passed to each task in the sequence.
  • A function returning a promise to be applied to each of the above.
  • A function to be executed for each result.

which means we can do this:

    const resolveInNSeconds = (n) => {
      return new Promise((resolve) => {
        setTimeout(() => resolve(n), n * 1000);
      })
    };

    const logResult = (result) => {
      console.log(result);
    }

    sequencer([2,3,5], resolveInNSeconds, logResult)
Enter fullscreen mode Exit fullscreen mode

Does this look like sound javascript?

I can't help thinking the resolveInNSeconds function could be a bit simpler?