DEV Community

KISHAN RAMLAKHAN NISHAD
KISHAN RAMLAKHAN NISHAD

Posted on

learn promise and asyn await with A basic example

function getBread() {
    // This declares a function named getBread that returns a Promise
    // A Promise is an object representing the eventual completion or failure 
    // of an asynchronous operation

    return new Promise((resolve, reject) => {
        // Creates a new Promise object
        // It takes a function with two arguments:
        // - resolve: a function called when the promise is successful
        // - reject: a function called when the promise encounters an error

        setTimeout(() => {
            // setTimeout is a web API that creates a delayed execution
            // It takes two arguments:
            // 1. A callback function to execute
            // 2. The delay time in milliseconds (1000ms = 1 second)

            console.log('Got the bread!');
            // This will print a message to the console

            resolve('Bread');
            // Resolves the promise with the value 'Bread'
            // This means the promise is successful and returns 'Bread'
        }, 1000);
        // The delay of 1000 milliseconds (1 second) simulates 
        // an asynchronous operation like fetching bread from a store
    });
}

getBread()
// This line calls the getBread() function
// At this point, it will:
// 1. Start the Promise
// 2. Wait 1 second
// 3. Log 'Got the bread!'
// 4. Resolve with the value 'Bread'

// However, without .then() or await, nothing will happen with the returned Promise

getBread().then((a) => {
    console.log(a);  // This will log 'Bread'
});
Enter fullscreen mode Exit fullscreen mode
function getBread() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log('Got the bread!');
            resolve('Bread');
        }, 1000);
    });
}

function addFillings(bread) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log('Added fillings!');
            resolve(bread + ' with Fillings');
        }, 1000);
    });
}

function serve(sandwich) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log('Sandwich is ready to eat!');
            resolve(sandwich);
        }, 1000);
    });
}

// Chaining the Promises
getBread()
    .then(addFillings)
    .then(serve)
    .then(finalProduct => console.log(`Enjoy your ${finalProduct}!`))
    .catch(error => console.log(`Something went wrong: ${error}`));
Enter fullscreen mode Exit fullscreen mode

output

Got the bread!
Added fillings!
Sandwich is ready to eat!
Enjoy your Bread with Fillings!

HERE WE ARE USING ASYN AWAIT

function getBread() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            // console.log('Got the bread!');
            resolve('Bread');
        }, 1000);
    });
}

function addFillings(bread) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log('Added fillings!');
            resolve(bread + ' with Fillings');
        }, 1000);
    });
}

function serve(sandwich) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log('Sandwich is ready to eat!');
            resolve(sandwich);
        }, 1000);
    });
}





    async function makeSandwich() {
        try {
            const bread = await getBread();
            const sandwichWithFillings = await addFillings(bread);
            const finalSandwich = await serve(sandwichWithFillings);
            console.log(`Enjoy your ${finalSandwich}!`);
        } catch (error) {
            console.log('Something went wrong:', error);
        }
    }

    makeSandwich();
Enter fullscreen mode Exit fullscreen mode

OUTPUT
Got the bread!
Added fillings!
Sandwich is ready to eat!
Enjoy your Bread with Fillings!

Image of Bright Data

Ensure Data Quality Across Sources – Manage and normalize data effortlessly.

Maintain high-quality, consistent data across multiple sources with our efficient data management tools.

Manage Data

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