Async/Await in JavaScript: From Callbacks to Clean Code
JavaScript's evolution from callback hell to clean async code.
The Evolution
Stage 1: Callbacks (The Dark Ages)
// Callback hell: nested, hard to read, error-prone getUser ( id , ( user ) => { getPosts ( user . id , ( posts ) => { getComments ( posts [ 0 ]. id , ( comments ) => { getAuthor ( comments [ 0 ]. authorId , ( author ) => { console . log ( author . name ); // Error handling? Good luck. }); }); }); });
Enter fullscreen mode
Exit fullscreen mode
Stage 2: Promises (Better)
// Flat chain but still verbose getUser ( id ) . then ( user => getPosts ( user . id )) . then ( posts => getComments ( posts [ 0 ]. id )) . then ( comments => getAuthor ( comments [ 0 ]. authorId )) . then ( author => console . log ( author . name )) . catch ( err => console . error ( ' Something failed: ' , err ));
Enter fullscreen mode
Exit fullscreen mode
Stage 3: Async/Await (Modern)
// Reads like synchronous code!…