Async/Await and How to use this in JavaScript?

Take it that your friend is returning to the library to borrow you some books. You would not simply continue to wait but read a magazine or do other activities while waiting. Here's how async/await works in a simple scenario.

Async: All that means is that the information exchange does not happen at the same time but instead, it's like asking a friend to go to the library to get the book while you do your thing.

Await: This is as saying "Only do the following after this is complete." It's like requesting one's friend to convey the message after he/she finishes the book and then move on to another work.

Here's a basic example using async/await in JavaScript:

// Imagine this function is like sending your friend to the library
async function getBookFromLibrary() {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve("Harry Potter"); // Simulate getting the book after a delay
        }, 2000); // 2 seconds delay

// Now, you want to read a magazine while your friend gets the book
async function readMagazine() {
    console.log("Reading a magazine while waiting for the book...");

// Here's where you put everything together
async function getBookAndRead() {
    await readMagazine(); // You start reading the magazine

    const book = await getBookFromLibrary(); // Your friend goes to the library and gets the book, and you wait for them to come back

    console.log("Got the book:", book); // Once your friend comes back, you get the book and continue doing what you were doing

// Now, you call the function to start the process

getBookFromLibrary()  is like sending your friend to the library.

readMagazine() is like reading a magazine while you wait.

getBookAndRead() is like coordinating everything, making sure you start reading the magazine first, then get the book when your friend returns from the library.

Thus, async/await lets you write asynchronous code as a sequence in contrast to the regular way of doing multiple tasks at the same time but waiting for one thing to finish before going further like in real life.


Post a Comment


© Copyright 2024 & 2025 - Team Krope - All right reserved