DEV Community

Cover image for Javascript Callbacks, Promises, and Async/Await ๐Ÿ•ฐ๏ธ
Shivam Singh
Shivam Singh

Posted on โ€ข Edited on

3 1 1 1 1

Javascript Callbacks, Promises, and Async/Await ๐Ÿ•ฐ๏ธ

Cracking the Code of Asynchronous JavaScript: Callbacks, Promises, and Async/Await ๐Ÿš€

Hey there, asynchronous astronauts! ๐Ÿš€ Are you tired of waiting? So is your JavaScript code. It's time to dive deep into the murky depths of asynchronous programming. We'll laugh, we'll cry, we'll question our career choices, but most importantly, we'll learn. So buckle up, because this spaceship is ready for takeoff!


1๏ธโƒฃ The Callback Confusion: More Nesting Than a Birdhouse ๐Ÿฆ

Callbacks! Ah, the grandpa of asynchronous code. They're not elegant, they're not pretty, but boy, do they get the job doneโ€”or at least, try to. The problem? Callback Hell. Let me demonstrate:

getUser(1, function(user) {
    getPosts(user.id, function(posts) {
        getComments(posts[0].id, function(comments) {
            // Someone, get me out of here!
        });
    });
});
Enter fullscreen mode Exit fullscreen mode

Callback Hell: populationโ€”you. Don't worry, JavaScript evolved, and so can you.


2๏ธโƒฃ I Promise, It Gets Better: Promises ๐Ÿคž

Promises are the JavaScript way of saying, "Don't call us, we'll call you." Simply put, promises have three states: pending, fulfilled, and rejected.

const myPromise = new Promise((resolve, reject) => {
    // Some code here
});

// Usage
myPromise.then(value => {
    console.log(value);
}).catch(reason => {
    console.error(reason);
});
Enter fullscreen mode Exit fullscreen mode

Ah, clean code, just like mom used to write.


3๏ธโƒฃ Chaining Promises: Link 'Em Up! โ›“๏ธ

If callbacks are Russian dolls, then chained promises are like...well, a less annoying version of Russian dolls.

getUser(1)
    .then(user => getPosts(user.id))
    .then(posts => getComments(posts[0].id))
    .then(console.log)
    .catch(console.error);
Enter fullscreen mode Exit fullscreen mode

That's how we like it, nice and clean!


4๏ธโƒฃ Async and Await: Await For It... ๐Ÿ•ฐ๏ธ

Why bother with .then() and .catch() when you can use async and await? This is like going from a flip phone to a smartphone.

async function run() {
    const user = await getUser(1);
    const posts = await getPosts(user.id);
    const comments = await getComments(posts[0].id);
    console.log(comments);
}
Enter fullscreen mode Exit fullscreen mode

Code so clean, you can eat off it.


5๏ธโƒฃ Try and Catch Me If You Can ๐ŸŽฃ

Combine async/await with try/catch and you're an unstoppable force.

async function run() {
    try {
        const user = await getUser(1);
        const posts = await getPosts(user.id);
        console.log(posts);
    } catch (err) {
        console.error(err);
    }
}
Enter fullscreen mode Exit fullscreen mode

Error handling like a pro!


6๏ธโƒฃ Parallel Execution: Multitasking Level ๐Ÿ’ฏ

Why wait for one thing when you can wait for all the things?

Promise.all([getUser(1), getPosts(1)]).then(([user, posts]) => {
    console.log(user, posts);
});
Enter fullscreen mode Exit fullscreen mode

Yeah, baby, that's what I'm talking about!


7๏ธโƒฃ Event Loop: The JavaScript Time Lord ๐Ÿ•ฐ๏ธ

The event loop allows JavaScript to perform asynchronous operations, despite being single-threaded. No example here, it's more of a concept, but let's just say if JavaScript were Doctor Who, the Event Loop would be the TARDIS.


8๏ธโƒฃ Queue Micro-Task: The Tiniest Taskmaster ๐Ÿœ

Did you know that promises and process.nextTick add tasks to the micro-task queue? Now you do!

console.log('1');
Promise.resolve().then(() => console.log('2'));
console.log('3');
Enter fullscreen mode Exit fullscreen mode

Order: 1, 3, 2. Thatโ€™s the micro-task queue for ya!


Conclusion

Hey, we made it through without tearing our hair out! ๐Ÿฅณ If youโ€™ve made it this far, congratsโ€”you now have a shiny toolbox full of asynchronous magic. Got questions, existential or JavaScript-related? Drop them in the comments below.๐Ÿ‘‡

Remember, asynchronous code doesn't have to be a pain. Like a magician ๐ŸŽฉ, you too can master the art of making things appear (and disappear) seamlessly. Keep practicing, and may your code be ever asynchronous!


Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs