📖 Understanding Promises in JavaScript

A promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. A promise can be in one of three states: pending, fulfilled, or rejected.

Promise Syntax


let condition = true; // Change this to false to test the reject case

let promise = new Promise(function(resolve, reject) {
    if (condition) {
        resolve("Promise is resolved successfully.");
    } else {
        reject("Promise is rejected.");
    }
});

// Handling the promise
promise
    .then(function(value) { console.log(value); }) // Success handler
    .catch(function(error) { console.log(error); }); // Error handler
        

The Promise constructor takes a function called the executor as its argument. The executor function has two parameters: resolve and reject. Call resolve when the asynchronous task is successfully completed and reject if there is an error.

The then method is used to specify what to do when the promise is resolved (fulfilled), and the catch method is used to specify what to do when the promise is rejected (fails).

Simulating Async Operations with Promises

We can use promises to simulate asynchronous operations like waiting for a timeout or performing a calculation.


// Simulating an asynchronous operation using setTimeout
function asyncOperation() {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            resolve("Asynchronous operation completed.");
        }, 2000);
    });
}

asyncOperation()
    .then(function(message) {
        console.log(message); // Output: Asynchronous operation completed.
    })
    .catch(function(error) {
        console.log(error);
    });
        

Chaining Promises

Chaining promises allows you to execute multiple asynchronous operations in sequence, with each subsequent operation starting when the previous one completes.


function firstAsyncOperation() {
    return new Promise(function(resolve) {
        setTimeout(function() {
            resolve("First operation completed.");
        }, 1000);
    });
}

function secondAsyncOperation() {
    return new Promise(function(resolve) {
        setTimeout(function() {
            resolve("Second operation completed.");
        }, 1000);
    });
}

firstAsyncOperation()
    .then(function(result) {
        console.log(result); // Output: First operation completed.
        return secondAsyncOperation();
    })
    .then(function(result) {
        console.log(result); // Output: Second operation completed.
    })
    .catch(function(error) {
        console.log(error);
    });
        

Putting It Into Action

To see these examples in action, create an HTML file and include the following script. This script will demonstrate the core principles of promises and log the results to the console.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promises Example</title>
</head>
<body>
    <script>
        // Example: Creating a Promise
        let condition = true; // Change this to false to test the reject case

        let myPromise = new Promise(function(resolve, reject) {
            if (condition) {
                resolve("Promise is resolved successfully.");
            } else {
                reject("Promise is rejected.");
            }
        });

        myPromise
            .then(function(value) { console.log(value); }) // Success handler
            .catch(function(error) { console.log(error); }); // Error handler

        // Simulating an asynchronous operation using setTimeout
        function asyncOperation() {
            return new Promise(function(resolve, reject) {
                setTimeout(function() {
                    resolve("Asynchronous operation completed.");
                }, 2000);
            });
        }

        asyncOperation()
            .then(function(message) {
                console.log(message); // Output: Asynchronous operation completed.
            })
            .catch(function(error) {
                console.log(error);
            });

        // Example: Chaining Promises
        function firstAsyncOperation() {
            return new Promise(function(resolve) {
                setTimeout(function() {
                    resolve("First operation completed.");
                }, 1000);
            });
        }

        function secondAsyncOperation() {
            return new Promise(function(resolve) {
                setTimeout(function() {
                    resolve("Second operation completed.");
                }, 1000);
            });
        }

        firstAsyncOperation()
            .then(function(result) {
                console.log(result); // Output: First operation completed.
                return secondAsyncOperation();
            })
            .then(function(result) {
                console.log(result); // Output: Second operation completed.
            })
            .catch(function(error) {
                console.log(error);
            });
    </script>
</body>
</html>
        

Challenge

This challenge builds on the "Putting It Into Action" example. Modify the asynchronous operations example to include a third operation and ensure all operations are chained correctly.

In order to check your learning, you should attempt to create a solution before revealing the provided solution below.


function firstAsyncOperation() {
    return new Promise(function(resolve) {
        setTimeout(function() {
            resolve("First operation completed.");
        }, 1000);
    });
}

function secondAsyncOperation() {
    return new Promise(function(resolve) {
        setTimeout(function() {
            resolve("Second operation completed.");
        }, 1000);
    });
}

function thirdAsyncOperation() {
    return new Promise(function(resolve) {
        setTimeout(function() {
            resolve("Third operation completed.");
        }, 1000);
    });
}

firstAsyncOperation()
    .then(function(result) {
        console.log(result); // Output: First operation completed.
        return secondAsyncOperation();
    })
    .then(function(result) {
        console.log(result); // Output: Second operation completed.
        return thirdAsyncOperation();
    })
    .then(function(result) {
        console.log(result); // Output: Third operation completed.
    })
    .catch(function(error) {
        console.log(error);
    });
                        

References