DEV Community

Cover image for Async Arrow Functions in TypeScript (With React Examples)
Arka Chakraborty
Arka Chakraborty

Posted on

Async Arrow Functions in TypeScript (With React Examples)

📌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 asyncwith 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); }; 
Enter fullscreen mode Exit fullscreen mode

📝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)