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.