Skip to content
Advertisement

promise doesn’t work, how to use catch in this way? [closed]

I’m trying to use promise to make error message to the console when Mongo connection doesn’t work. i get an error: Cannot read properties of undefined (reading ‘catch’) how can i fix it? it supposed to work like that. i can use try & catch block but i prefer to know how to use it this way and what is wrong

mongoose
  .connect(DB, {
    useNewUrlParser: true,
    useCreatIndex: true,
    useFindAndModify: false,
  })
  .then(() => {
    console.log('DB conecttion successful')
    .catch(() => console.log('Error'));
  });

const port = 3000;
app.listen(port, () => {
  console.log(`app runing on port ${port}`);
});

Advertisement

Answer

catch should be after then not after console.

console.log will return undefined as it void function, that why the error "Cannot read properties of undefined" appear

mongoose
  .connect(DB, {
    useNewUrlParser: true,
    useCreatIndex: true,
    useFindAndModify: false,
  })
  .then(() => {
    console.log('DB conecttion successful')
  }).catch(() => console.log('Error'));;

const port = 3000;
app.listen(port, () => {
  console.log(`app runing on port ${port}`);
});
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement