the code that I have, I need to change the endpont /specialOperation to asynchronously (with your utility module) get the grade result and rectangle result like this( promises required):

Database System Concepts
7th Edition
ISBN:9780078022159
Author:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Chapter1: Introduction
Section: Chapter Questions
Problem 1PE
icon
Related questions
Question

the code that I have, I need to change the endpont /specialOperation to asynchronously (with your utility module) get the grade result and rectangle result like this( promises required):

{"gradeStats":{"average":86.25,"minimum":73,"maximum":97},"rectangle":{"area":8,"perimeter":12}}

1) 

require('dotenv').config();

const calculator = require('./asyncCalculator');

const express = require('express');
const { response } = require('express');
const app = express();
app.get('/gradeStats', gradeStats);
app.get('/rectangle', rectangle);
app.get('/specialOperation', specialOperation);

const listener = app.listen(process.env.PORT, process.env.HOST, () => {
  console.log(`Server listening at ${listener.address().address}:${listener.address().port}`);
});

function gradeStats(req, res) {
  calculator.gradeStats(req.query.grade)
    .then((result) => { res.json({ result: result }) })
    .catch((error) => { res.status(400).json({ error: error.message }) });
}

function rectangle(req, res) {
    const length = parseInt(req.query.length);
    const width = parseInt(req.query.width);
    calculator.rectangle(length, width)
      .then((response) => { res.json({ result: response }) })
      .catch((error) => { res.status(400).json({ error: error.message }) });
}

function specialOperation(req, res) {
    const { length, width, grade: gradeString } = req.query;
    calculator.specialOperation(gradeString, parseInt(length), parseInt(width))
      .then(({result}) => { res.json({ result: result }) })
      .catch((error) => { res.status(400).json({ error: error.message }) });
    }
2)
async function gradeStats(grade) {
    const promise = new Promise((resolve, reject) => {
        setTimeout(function() {
            if (!grade) {
                reject(new Error("Error: grade is undefined."));
                return;
            }
            for (const g of grade) {
                if (isNaN(g)) {
                    reject(new Error("Grades should only contain numbers."));
                    return;
                }
            }
            const numGrades = grade.map(g => parseInt(g, 10));
            const min = Math.min(...numGrades);
            const max = Math.max(...numGrades);
            const avg = (numGrades.reduce((a, b) => a + b) / numGrades.length).toFixed(2);
            const result = { average: avg, minimum: min, maximum: max };
            resolve(result);
        }, 0);
    });
    return promise;
}

async function rectangle(length, width) {
    const promise = new Promise((resolve, reject) => {
        setTimeout(function() {
            if (isNaN(length) || isNaN(width)) {

                reject(new Error("Both length and width are required parameters." ));
       
            } else if (length === undefined || width === undefined) {
       
                reject(new Error("Both length and width are required parameters."));
       
            } else if (length <= 0 || width <= 0) {
       
                reject(new Error("Both length and width must be greater than 0." ));
       
            } else {
                const area = length * width;
                const perimeter = 2 * (length + width);
                const response = {area, perimeter};
       
                resolve(response);
            }
        });
    });
    return promise;
}

async function specialOperation(gradeString, length, width) {
    const promise = new Promise((resolve, reject) => {
        const promise1 = new Promise((resolve, reject) => {
          if (!gradeString) {
            reject(new Error("Grades parameter is missing."));
            return;
          }
          const grade = String(gradeString).split(",").map(Number);
          const min = Math.min(...grade);
          const max = Math.max(...grade);
          const avg = (grade.reduce((a, b) => a + b) / grade.length).toFixed(2);
          resolve({ average: parseFloat(avg), minimum: min, maximum: max });
        });
   
        const promise2 = new Promise((resolve, reject) => {
          setTimeout(() => {
            try {
              const area = length * width;
              const perimeter = 2 * (length + width);
              resolve({ area, perimeter });
            } catch (error) {
              reject("An error occurred");
            }
          }, 2000);
        });
        Promise.all([promise1, promise2])
        .then(([gradeStats, rectangle]) => {
          const result = { gradeStats, rectangle };
          resolve(result);
        })
        .catch((error) => {
          reject(error);
        });
    });
}
 
  function validateOperands(a, b, reject) {
    if (a === undefined || b === undefined)
      reject(new Error('Both a and b are required.'));
 
    if (isNaN(a) || isNaN(b))
      reject(new Error('Both a and b must be numbers.'));
  }


 
  module.exports = {
    dotted,
    fizzBuzz,
    gradeStats,
    rectangle,
    specialOperation,
  };
Expert Solution
Step 1 ans

Here's how you can modify the specialOperation function to use promises and make the necessary calls to gradeStats and rectangle asynchronously:

async function specialOperation(gradeString, length, width) {
  const promise1 = new Promise((resolve, reject) => {
    if (!gradeString) {
      reject(new Error("Grades parameter is missing."));
      return;
    }
    const grade = String(gradeString).split(",").map(Number);
    calculator.gradeStats(grade)
      .then((result) => resolve(result))
      .catch((error) => reject(error));
  });

  const promise2 = new Promise((resolve, reject) => {
    calculator.rectangle(length, width)
      .then((result) => resolve(result))
      .catch((error) => reject(error));
  });

  const [gradeStatsResult, rectangleResult] = await Promise.all([promise1, promise2]);
  const result = { gradeStats: gradeStatsResult, rectangle: rectangleResult };
  return result;
}

trending now

Trending now

This is a popular solution!

steps

Step by step

Solved in 2 steps

Blurred answer
Knowledge Booster
Top down approach design
Learn more about
Need a deep-dive on the concept behind this application? Look no further. Learn more about this topic, computer-science and related others by exploring similar questions and additional content below.
Similar questions
  • SEE MORE QUESTIONS
Recommended textbooks for you
Database System Concepts
Database System Concepts
Computer Science
ISBN:
9780078022159
Author:
Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:
McGraw-Hill Education
Starting Out with Python (4th Edition)
Starting Out with Python (4th Edition)
Computer Science
ISBN:
9780134444321
Author:
Tony Gaddis
Publisher:
PEARSON
Digital Fundamentals (11th Edition)
Digital Fundamentals (11th Edition)
Computer Science
ISBN:
9780132737968
Author:
Thomas L. Floyd
Publisher:
PEARSON
C How to Program (8th Edition)
C How to Program (8th Edition)
Computer Science
ISBN:
9780133976892
Author:
Paul J. Deitel, Harvey Deitel
Publisher:
PEARSON
Database Systems: Design, Implementation, & Manag…
Database Systems: Design, Implementation, & Manag…
Computer Science
ISBN:
9781337627900
Author:
Carlos Coronel, Steven Morris
Publisher:
Cengage Learning
Programmable Logic Controllers
Programmable Logic Controllers
Computer Science
ISBN:
9780073373843
Author:
Frank D. Petruzella
Publisher:
McGraw-Hill Education