DEV Community

Cover image for Javascript Callbacks, Promises, and Async/Await πŸ•°οΈ
Shivam Singh
Shivam Singh

Posted on • Updated on

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)