I am experiencing issues with my asynchronous request in Express

I'm currently in the process of transitioning my requests to async calls to prevent them from blocking.

app.js

app.use(function(err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};
  console.log(err);
  res.status(err.status || 500);
  res.json({ error: err.message });
});

route

router.get(
  "/seatData/:seatNumber",
  [
    check("seatNumber")
      .matches(/^[0-9][a-z]$/i)
      .withMessage("must start with a number(0-9) and end with a letter")
  ],
  actions.fetch_seat
);

controller

exports.fetch_seat = (req, res, next) => {
  Seat.getSeatByNumber(req.params.seatNumber, (err, seat) => {
    if (err) res.json(err);
    else res.json(seat);
  });
};

model

Seat.findSeat = function(key, value) {
  return new Promise((resolve, reject) => {
    const seat = file.find(r => r[key] === value);
    if (!seat) {
      reject({
        error: true,
        message: "Seat not found",
        status: 404
      });
    }
    resolve(seat);
  });
};

Seat.getSeatByNumber = function(seatNumber, result, next) {
  try {
    this.seat = this.findSeat("seatNumber", seatNumber)
      .then(seat => {
        if (seat !== undefined && Object.keys(seat).length > 0) {
          result(null, seat);
        } else {
          result({ error: true, message: "Seat not found" });
        }
      })
      .catch(error => {
        return;
      });
  } catch (error) {
    console.log(error);
  }
};

I've followed some online guides but can't seem to properly get the error response back to express. The code within /* ... */ is the original code I'm attempting to convert.

UPDATE

What is the difference between the 1st catch and the 2nd catch? Also, why doesn't my app.js catch the status code I returned?

Seat.findSeat = function(key, value) {
  return new Promise((resolve, reject) => {
    const seat = file.find(r => r[key] === value);
    if (!seat) {
      reject({
        error: true,
        message: "Seat not found",
        status: 404
      });
    }
    resolve(seat);
  });

};

Seat.getSeatByNumber = function(seatNumber, result, next) {
  try {
    this.seat = this.findSeat("seatNumber", seatNumber)
      .then(seat => {
        console.log(seat);
        if (seat !== undefined && Object.keys(seat).length > 0) {
          result(null, seat);
        } else {
          result({ error: true, message: "Seat not found" });
        }
      })
      .catch(error => {
        console.log("1st catch");
        return result(error);
      });
  } catch (error) {
    console.log("outer catch");
    console.log(error);
    result(error);
  }

};

app.js The errors are not being logged here

app.use(function(err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};
  console.log('apperro' , err) // <-- does not log this
  res.status(err.status || 500);
  res.json({ error: err.message });
});

UPDATE 2

After adding next, I encounter the following error. You can input seatData/1T into the URL within the sandbox https://codesandbox.io/s/elucidate-api-fokd8

(node:319) UnhandledPromiseRejectionWarning: TypeError: next is not a function
    at Seat.getSeatByNumber (/sandbox/src/controller/appController.js:15:14)
    at findSeat.then.catch.error (/sandbox/src/model/seat.js:45:16)
(node:319) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:319) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Answer №1

It appears that you are looking to handle errors in a more structured way when they are returned from your model file to your controller.

It seems that you have omitted returning the error in the catch blocks within your model file.

Instead of simply using return or console.log(error) in your catch blocks, it is recommended to utilize your result object like this: result(error);

UPDATE:

Within your controller, you are currently utilizing res.json(). To effectively pass control to the next defined step in your app.use chain, consider using next() with appropriate parameters rather than res.json().

When using res.json(), the response is sent as JSON and the process stops there.

UPDATE 2:

exports.fetch_seat = (req, res, next) => {
  Seat.getSeatByNumber(req.params.seatNumber, (err, seat) => {
    if (err) next(err); // Pass error back to express middleware
    else res.json(seat); // No error, respond immediately
  });
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjust the position of an object in Three.js based on the scale of another object

Sharing a helpful solution for a recent problem I faced in case it can assist someone else. Imagine you have a House object with a Chair inside it positioned in a particular spot. If you scale the House's size by 2, the Chair will no longer be in the ...

Unleashing the power of express-fileupload for uploading large files

Currently, I am utilizing the express-fileupload npm package to handle multipart file uploads. The challenge I am facing is the need to upload multiple files where the size exceeds the default limit of 100kb. In order to accommodate larger file sizes, I ha ...

"Exploring the power of asynchronous operations in NodeJS using Q

Currently, I am utilizing Node.js and I aim to incorporate promises to ensure a complete response following a for loop. exports.getAlerts = function(req,res,next){ var detected_beacons = []; if (!req.body || Object.keys(req.body).length == 0) { res.s ...

Obtaining the clientID when the textbox name is stored in a string variable

I am struggling with the following code intended to check for a blank value in my textbox, but it is resulting in a compilation error. Can someone help me find a solution? Here is my code in JavaScript: function checkTextboxNotFilled(txtbox) { v ...

How can I display a badge in my app when it is running using React Native?

For the past week, I've been dealing with an issue. My question is how can I display a new message badge without having to click on the message room when running my app. The badge should only show up after clicking on the message room. I see the badg ...

Purge session files that have expired in the session-file store

I have implemented session-file-store to manage sessions in my Node-Express application. With session-file-store, a new file is created for each session, leading to an accumulation of files on the server over time. Is there a method or configuration opti ...

Form validation using JQuery within a Bootstrap 4 modal incorporating tabs is preventing submission

Encountering a challenge with JQuery Validation within a modal that contains tabs. When I'm on the Sign-in Tab and click the Login button, the validation errors display correctly: https://i.sstatic.net/caReK.jpg ISSUE 1 However, on the New Account ...

Adding quotes is optional when using the append function

We are retrieving product options from the displayed html using variables PRODUCT_CUSTOM_1_ and PRODUCT_NAME_. Some products have quotations like " and '. However, when we post these strings elsewhere, they get cut off at the ". We need to either remo ...

The Redis port and host remain unset despite having defined environment variables

While utilizing the redis npm package, I encountered an issue where the host and port values were showing as undefined when trying to connect. Even after checking my process.env object, I could see that the values were properly set. Strangely, it only beca ...

Getting the dimensions of an image using a path in JavaScript

I am trying to display a div with an image, its name, size, and download link using jQuery. Here is the code I have created: var image = 'image/example.png' $('#download').attr("href", result2); $('.image').attr("src", re ...

Conceal the Angular alert message automatically after a specified number of seconds or when the page

I recently started working with Angular and managed to implement an alert message for password reset requests in our app: Usermodel: .service('userModel', ['$q', '$http', 'authorizedTracker', function($q, $http, au ...

What could be causing the issue of messages not displaying while incorporating connect-flash with res.locals in express.js and ejs templating?

Here are some snippets of code that may be useful. Connect-flash is designed to display messages on test1 and test2, but there seems to be an issue with displaying messages for test 3: user registration when all three tests are redirected to the same &apos ...

What is the best way to extract raw data from a kendo dataSource?

After fetching data for my Kendo grid from the backend and populating it in the alignedProcessesToRiskGridOptions, I noticed that while the data is displayed in the grid, I also need access to the raw data for additional logic. Is there a way to retrieve d ...

Plugin for turning text into "leet speak" using jQuery and Javascript

Recently, I've been on the hunt for a 1337 translator that I can seamlessly integrate into a jQuery plugin. While I believe I'm making progress, I can't shake off the feeling that something's amiss. My gut tells me that what I currently ...

I am constantly encountering the error message "Reading 'Linear'' error due to undefined properties in my threejs code

A procedural generation library for threejs caught my attention Here is the link to the library: https://github.com/IceCreamYou/THREE.Terrain Despite following the instructions provided in the ReadMe.md file, I encountered an error that says: Cannot read ...

Exploring the intricacies of multidimensional array scopes in AngularJS

I have a JSON value that includes a list of countries and states. I want to split this value into two different scopes: $scope.countries and $scope.states. When the country is changed, the state should change based on the selected country. Sample JSON da ...

Guide to transmitting form-data and files from API Gateway to backend Node.js service API?

My query is not too big, but I need to send a file and some data to a backend service through an API gateway. I prefer to avoid any preprocessing at the API gateway level and handle everything in the backend service. Request from user ---> Api-Ga ...

Controlling Node.js application with Electron app: initiating and terminating

I'm currently working on the functionality to control the start and stop of another node.js application within my electron app. So far, I've managed to successfully start the node application from bot.js by running npm start to launch the electr ...

The return value from vue-query is ObjectRefImpl, not the actual data

Greetings to the Vue.js community! As a newcomer to Vue.js, I am seeking guidance on fetching data using vue-query, Vue.js 3, and the composition API. The data returned to me is ObjectRefImpl, but when I try to print the values, I encounter the error: "Pro ...

CSS ID selectors are not functioning properly

In my React.JS project, I am working with a div that contains a button and a list. The list is specifically identified by the id "results". return <div> <Button label="Combine Cards" disabled={!this.props.combineReady} onClick={this.handleCli ...