Asynchronous Javascript

Greetings, code wizard! Today, we are stepping into the mystical realm of Asynchronous JavaScript.

Where tasks don't need to wait for their turn and the spells you cast won't necessarily complete in the order you chant them. Fasten your magic cape, let's dive in!

Callbacks

In the magical world of JavaScript, a callback is like a familiar—a loyal creature you entrust with a task to complete. You carry on with your wizarding duties, and it will dutifully inform you when its task is complete. Here's how a callback function might look:

function brewPotion(ingredient, callback) {
    console.log(`Brewing potion with ${ingredient}...`);
    setTimeout(() => {
        console.log('Potion brewed!');
        callback();
    }, 2000);
}

brewPotion('dragon scale', () => {
    console.log('Hurray! Time to have some fun with magic!');
});

Here, setTimeout is used to simulate a task (like fetching data from a server) that takes time to complete.

Promises

A Promise is like an enchanted orb—it can be in one of three states: pending, fulfilled, or rejected. Once it's either fulfilled or rejected, it can't change its state again—it's immutable, just like the future seen in a prophecy.

let readTheProphecy = new Promise((resolve, reject) => {
    let prophecyWritten = true;

    if (prophecyWritten) {
        resolve("The prophecy tells of great JavaScript knowledge in your future.");
    } else {
        reject("The prophecy is yet to be written.");
    }
});

readTheProphecy.then(message => {
    console.log(`Fulfilled: ${message}`);
}).catch(error => {
    console.log(`Rejected: ${error}`);
});

In the example above, readTheProphecy is a promise. If prophecyWritten is true, the promise is fulfilled, else it's rejected.

Async/Await

While callbacks and promises are undoubtedly magical, they can lead to what some sorcerers refer to as "callback hell" or "promise hell" when things get complicated. That's when async/await swoops in like a magic carpet to the rescue!

async/await is built on promises, but it allows you to work with promises as if they were synchronous. Let's look at how to create a magical potion using async/await:

function brewPotionAsync(ingredient) {
    return new Promise((resolve) => {
        console.log(`Brewing potion with ${ingredient}...`);
        setTimeout(() => {
            console.log('Potion brewed!');
            resolve();
        }, 2000);
    });
}

async function performMagic() {
    await brewPotionAsync('phoenix feather');
    console.log('Hurray! Time to have some fun with magic!');
}

performMagic();

The function brewPotionAsync returns a promise that resolves after 2 seconds. In the performMagic function, we use the await keyword to pause execution until the promise is resolved. This gives us much cleaner, easier-to-read code.

So, young wizard, remember: dealing with asynchronous code might seem daunting at first, but with the right spells like callbacks, promises, and async/await, you can harness the true power of JavaScript! Happy casting!

Previous Next

Written © 2024 Written Developer Tutorials and Posts.

đť•Ź