Build simple calculation with different approach Callbacks, Promises and Async/Await:

Callbacks Example:


    <div>
        <label>Enter First Number:</label>
        <input type="text" id="num1" name="num1" required />
    </div>
    <div>
        <label>Enter Second Number:</label>
        <input type="text" id="num2" name="num2" required />
    </div>
    <div>
        <label>Select Operation:</label>
        <select id="operation" name="operation">
            <option value="add">Add</option>
            <option value="subtract">Subtract</option>
            <option value="multiply">Multiply</option>
            <option value="divide">Divide</option>
        </select>
    </div>
    <button type="submit" onclick="calculate()">Calculate</button>
    <div id="result"></div>

    <script>
        function add(a, b, callback) {
            setTimeout(() => {
                callback(a + b);
            }, 2000);
        }

        function subtract(a, b, callback) {
            setTimeout(() => {
                callback(a - b);
            }, 2000);
        }

        function multiply(a, b, callback) {
            setTimeout(() => {
                callback(a * b);
            }, 2000);
        }

        function divide(a, b, callback) {
            setTimeout(() => {
                callback(a / b);
            }, 2000);
        }

        function calculate() {
            const num1 = parseFloat(document.getElementById("num1").value);
            const num2 = parseFloat(document.getElementById("num2").value);
            const operation = document.getElementById("operation").value;

            switch (operation) {
                case "add":
                    add(num1, num2, (result) => {
                        document.getElementById("result").innerHTML = `Result: ${result}`;
                    });
                    break;
                case "subtract":
                    subtract(num1, num2, (result) => {
                        document.getElementById("result").innerHTML = `Result: ${result}`;
                    });
                    break;
                case "multiply":
                    multiply(num1, num2, (result) => {
                        document.getElementById("result").innerHTML = `Result: ${result}`;
                    });
                    break;
                case "divide":
                    divide(num1, num2, (result) => {
                        if (num2 === 0) {
                            document.getElementById("result").innerHTML = `Cannot Divide by zero`;
                        } else {
                            document.getElementById("result").innerHTML = `Result: ${result}`;
                        }
                    });
                    break;
            }
        }
    </script>


Promises Example:


   <div>
        <label>Enter First Number:</label>
        <input type="text" id="num1" name="num1" required />
    </div>
    <div>
        <label>Enter Second Number:</label>
        <input type="text" id="num2" name="num2" required />
    </div>
    <div>
        <label>Select Operation:</label>
        <select id="operation" name="operation">
            <option value="add">Add</option>
            <option value="subtract">Subtract</option>
            <option value="multiply">Multiply</option>
            <option value="divide">Divide</option>
        </select>
    </div>
    <button type="submit" onclick="calculate()">Calculate</button>
    <div id="result"></div>

    <script>
        function add(a, b) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    if (isNaN(a) || isNaN(b)) {
                        reject(Error("Invalid Input"));
                    } else {
                        resolve(a + b);
                    }
                }, 2000);
            });
        }

        function subtract(a, b) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    if (isNaN(a) || isNaN(b)) {
                        reject(Error("Invalid Input"));
                    } else {
                        resolve(a - b);
                    }
                }, 2000);
            });
        }

        function multiply(a, b) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    if (isNaN(a) || isNaN(b)) {
                        reject(Error("Invalid Input"));
                    } else {
                        resolve(a * b);
                    }
                }, 2000);
            });
        }

        function divide(a, b) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    if (isNaN(a) || isNaN(b)) {
                        reject(Error("Invalid Input"));
                    } else if (b === 0) {
                        reject(Error("Cannot Divide by Zero"));
                    } else {
                        resolve(a / b);
                    }
                }, 2000);
            });
        }

        async function calculate() {
            try {
                const num1 = parseFloat(document.getElementById("num1").value);
                const num2 = parseFloat(document.getElementById("num2").value);
                const operation = document.getElementById("operation").value;

                switch (operation) {
                    case "add":
                        const addResult = await add(num1, num2);
                        document.getElementById("result").innerHTML = `Result: ${addResult}`;
                        break;
                    case "subtract":
                        const subtractResult = await subtract(num1, num2);
                        document.getElementById("result").innerHTML =
                            document.getElementById("result").innerHTML = `Result: ${subtractResult}`;
                        break;
                    case "multiply":
                        const multiplyResult = await multiply(num1, num2);
                        document.getElementById("result").innerHTML = `Result: ${multiplyResult}`;
                        break;
                    case "divide":
                        const divideResult = await divide(num1, num2);
                        document.getElementById("result").innerHTML = `Result: ${divideResult}`;
                        break;
                }
            } catch (error) {
                document.getElementById("result").innerHTML = error.message;
            }
        }
    </script>


Async/Await Example:


   
   <div>
        <label>Enter First Number:</label>
        <input type="text" id="num1" name="num1" required />
    </div>
    <div>
        <label>Enter Second Number:</label>
        <input type="text" id="num2" name="num2" required />
    </div>
    <div>
        <label>Select Operation:</label>
        <select id="operation" name="operation">
            <option value="add">Add</option>
            <option value="subtract">Subtract</option>
            <option value="multiply">Multiply</option>
            <option value="divide">Divide</option>
        </select>
    </div>
    <button type="submit" onclick="calculate()">Calculate</button>
    <div id="result"></div>

    <script>
        function add(a, b) {
            return new Promise((resolve, reject) => {
                if (isNaN(a) || isNaN(b)) {
                    reject(Error("Invalid Input"));
                } else {
                    resolve(a + b);
                }
            });
        }

        function subtract(a, b) {
            return new Promise((resolve, reject) => {
                if (isNaN(a) || isNaN(b)) {
                    reject(Error("Invalid Input"));
                } else {
                    resolve(a - b);
                }
            });
        }

        function multiply(a, b) {
            return new Promise((resolve, reject) => {
                if (isNaN(a) || isNaN(b)) {
                    reject(Error("Invalid Input"));
                } else {
                    resolve(a * b);
                }
            });
        }

        function divide(a, b) {
            return new Promise((resolve, reject) => {
                if (isNaN(a) || isNaN(b)) {
                    reject(Error("Invalid Input"));
                } else if (b === 0) {
                    reject(Error("Cannot Divide by Zero"));
                } else {
                    resolve(a / b);
                }
            });
        }

        async function calculate() {
            try {
                const num1 = parseFloat(document.getElementById("num1").value);
                const num2 = parseFloat(document.getElementById("num2").value);
                const operation = document.getElementById("operation").value;

                switch (operation) {
                    case "add":
                        const addResult = await add(num1, num2);
                        document.getElementById("result").innerHTML = `Result: ${addResult}`;
                        break;
                    case "subtract":
                        const subtractResult = await subtract(num1, num2);
                        document.getElementById("result").innerHTML = `Result: ${subtractResult}`;
                        break;
                    case "multiply":
                        const multiplyResult = await multiply(num1, num2);
                        document.getElementById("result").innerHTML = `Result: ${multiplyResult}`;
                        break;
                    case "divide":
                        const divideResult = await divide(num1, num2);
                        document.getElementById("result").innerHTML = `Result: ${divideResult}`;
                        break;
                }
            } catch (error) {
                document.getElementById("result").innerHTML = error.message;
            }
        }
    </script>ror
(error))


I hope this helps you understand the differences between these different ways to handle calculation with different approach Callbacks, Promises and Async/Await: 

Mudasir Abbas Turi

Hi, this is Mudasir Abbas Turi. I am a Full-stack PHP and JavaScript developer with extensive experience in building and maintaining web applications. Skilled in both front-end and back-end development, with a strong background in PHP and JavaScript. Proficient in modern web development frameworks such as Laravel and ReactJS. Proven ability to develop and implement highly interactive user interfaces, and to integrate with various APIs and databases. Strong problem-solving skills and ability to work independently and as part of a team. Passionate about staying up-to-date with the latest technologies and industry trends.

Post a Comment

Previous Post Next Post