Member-only story

The Power of Spread and Rest in Async Javascript

Take Your Async Code to the Next Level with These Clever Tricks

Max N
2 min readApr 2, 2024

JavaScript’s async/await feature has revolutionized the way we write asynchronous code, making it more readable and easier to reason about. However, even with this powerful tool, we sometimes encounter situations where our code can become a bit cumbersome or repetitive.

That’s where the spread syntax and rest parameters come in handy, helping us write cleaner and more concise asynchronous code.

Spreading the Love with Async Functions

Let’s start with the spread syntax, which allows us to spread the elements of an iterable (like an array or a string) into another array or as individual arguments to a function call. In the context of async functions, the spread syntax can be incredibly useful when dealing with promises that resolve to arrays or other iterables.

const fetchData = async () => {
const [user, posts] = await Promise.all([
fetch('/api/user').then(res => res.json()),
fetch('/api/posts').then(res => res.json())
]);
return { user, posts };
};

const handleData = async () => {
const { user, posts } = await fetchData();
console.log('User:', user);
console.log('Posts:', ...posts); // Spread the posts array…

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

No responses yet