Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

222
Visualizações
TypeError: Cannot read property 'then' of undefined using promises

I am making this website as a project which is a "Walmart" version of AirBnB.

Here's what the button is supposed to do for context:

A user will click on a "Make Reservation" button on a listing. They will select a start and end date then submit. This will send an HTTP request to the server.

However, I am running into an error where it returns :

TypeError: Cannot read property 'then' of undefined at /vagrant/LightBnB/LightBnB_WEB_APP/server/apiRoutes.js:44:7 <--

The line 44:7 is the API route below:

This is causing the error:

.then((reservation) => {
            res.send(reservation);

This is the API ROUTE Logic which is causing an issue:

  router.post('/reservations', (req, res) => {
    const userId = req.session.userId;
    database
      .addReservation({ ...req.body, guest_id: userId })
      .then((reservation) => {
        res.send(reservation);
      })
      .catch((e) => {
        console.error(e);
        res.send(e);
      });
  });

That route is calling the function addReservation() which is the following:

    /**
 * Add a reservation to the database
 * @param {{}} reservation An object containing all of the reservation details.
 * @return {Promise<{}>} A promise to the reservation.
 */
const addReservation = function (reservation) {
  const queryString = `
  INSERT INTO reservations(
    start_date,
    end_date,
    property_id,
    guest_id 
  ) 
  VALUES ($1, $2, $3, $4)
  RETURNING *
  `;
  const values = [
    reservation.start_date,
    reservation.end_date,
    reservation.property_id,
    reservation.guest_id,
  ];
  pool
    .query(queryString, values)
    .then((res) => {
      res.rows;
    })
    .catch((e) => console.log(e.message));
};
exports.addReservation = addReservation;

Please let me know if you need more information.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

TypeError: Cannot read property 'then' of undefined

addReservation() has no return value, thus it returns undefined. So, when you try to do addReservation(...).then(...), you end up trying to access .then() on undefined which results in the error you get.

Inside of addReservation(), you need to change:

pool.query(...).then(...).catch(...)

to

return pool.query(...).then(...).catch(...)

That returns your promise so then the caller can use .then() on the returned promise.


Note, your .catch() handler in addReservation() is logging and then "eating" the error. You should probably rethrow the error so that the caller can see the error:

Change this:

.catch((e) => console.log(e.message));

to this:

.catch((e) => {
     console.log(e.message)
     // re-throw the error so it propagates to the caller
     throw e;
});

Also, note that res.send(e) probably won't provide much useful info because most properties of the Error object are not enumerable and thus won't show up when res.send() turns the Error object into JSON.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda