Member-only story
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…