Menu

1 / 2

Async/Await in JavaScript: Writing Cleaner Asynchronous Code

DEV Community·Pratham·6 months ago
#eoshCxVn
#pattern#part#basic#with#await
Reading 0:00
15s threshold

Asynchronous code that reads like synchronous code — because sometimes the best upgrade is better syntax.

We've come a long way. Callbacks taught us how JavaScript handles async operations. Promises gave us flat chains and centralized error handling. But let me show you the next evolution:

// Promise chain getUser ( 1 ) . then (( user ) => getOrders ( user . id )) . then (( orders ) => getShipping ( orders [ 0 ]. id )) . then (( shipping ) => console . log ( shipping . address )) . catch (( err ) => console . log ( err ));

// Async/await — same logic async function showShippingAddress () { try { const user = await getUser ( 1 ); const orders = await getOrders ( user . id ); const shipping = await getShipping ( orders [ 0 ]. id ); console . log ( shipping . address ); } catch ( err ) { console . log ( err ); } }

Enter fullscreen mode

Exit fullscreen mode

Look at the async/await version. No .then() . No chaining. No callbacks.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.