Categories
JavaScript Answers

How to use JavaScript array .reduce with async/await?

Spread the love

Sometimes, we want to use JavaScript array .reduce with async/await.

In this article, we’ll look at how to use JavaScript array .reduce with async/await.

How to use JavaScript array .reduce with async/await?

To use JavaScript array .reduce with async/await, we can use the awaity library.

To install it, we run

npm install awaity

Then we use it by writing

import reduce from "awaity/reduce";

const posts = await reduce(
  [1, 2, 3],
  async (posts, id) => {
    const res = await fetch("/api/posts/" + id);
    const post = await res.json();

    return {
      ...posts,
      [id]: post,
    };
  },
  {}
);

to call the reduce function with the array we’re reducing and a callback that returns a promise.

We use await to get the result from fetch and return an object with reduced value.

Conclusion

To use JavaScript array .reduce with async/await, we can use the awaity library.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *