
Structured Concurrency in JavaScript: Beyond Promise.all
The Problem with Unstructured Async Code JavaScript async code has a scope problem. You fire off promises and hope they complete—or fail—cleanly. When something goes wrong mid-flight, cleanup is your responsibility. // Classic problem: partial failure async function loadDashboard ( userId : string ) { const [ user , orders , analytics ] = await Promise . all ([ getUser ( userId ), getOrders ( userId ), // This throws after 2 seconds getAnalytics ( userId ), // This is still running! ]); // getAnalytics never gets cancelled } When getOrders rejects, Promise.all rejects—but getAnalytics keeps running in the background, consuming resources, potentially writing stale data. Promise.allSettled: Handle All Results async function loadDashboard ( userId : string ) { const results = await Promise . allSettled ([ getUser ( userId ), getOrders ( userId ), getAnalytics ( userId ), ]); const [ userResult , ordersResult , analyticsResult ] = results ; // Handle each independently const user = userRes
Continue reading on Dev.to
Opens in a new tab

