📌Intro
In modern TypeScript (and React), arrow functions are everywhere. The good news: async
works perfectly with them.
đź§ Context
Arrow functions are used in event handlers, array methods, and inline logic. Knowing async
with arrows is essential.
Examples:
// Async arrow
const fetchData = async (): Promise<string> => {
const res = await fetch("/api/message");
const data = await res.json();
return data.message;
};
// React handler
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault();
const msg = await fetchData();
console.log("Message:", msg);
};
// With map + Promise.all
const urls = ["/a", "/b", "/c"];
const fetchAll = async () => {
const results = await Promise.all(
urls.map(async url => {
const res = await fetch(url);
return res.json();
})
);
console.log(results);
};
📝Real life examples
- Form submission in React (
onSubmit
). - Loading multiple APIs in parallel.
⚠️ forEach(async
...) doesn’t work as you expect. Always use map
+ Promise.all
.
Top comments (0)