unhandled promise rejection with react app

Viewed 37

So I tried to run npm start and i got : "(node:4786) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) (node:4786) [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."

This is the main code of the server I am trying to launch:

const express = require('express');
const app = express();
const cors = require('cors');
const connectDb = require('./src/database');
const faker = require('faker');

const User = require('./src/models/user.model');

// configure express to use cors()
// ------------------------------------------------------------------
app.use(cors());

app.get('/users', async (req, res) => {
  const users = await User.find();

  res.json(users);
});

app.get('/user-create', async (req, res) => {
  const user = new User({
    username: faker.internet.userName(),
    email: faker.internet.email(),
  });

  await user.save().then(() => console.log('User created'));

  res.send('User created \n');
});

app.get('/users-delete', async (req, res) => {
  await User.deleteMany({}).then(() => console.log('Users deleted'));

  res.send('Users deleted \n');
});

app.get('/', (req, res) => {
  res.send('Hello from Node.js app \n');
});

// start server
// -----------------------
app.listen(8080, function () {
  console.log('Running on port 8080! - http://localhost:8080');
  connectDb().then(() => console.log('MongoDb connected'));
});

I am unsure of how to fix this as this is assignment from my MIT course online and I did not write this code. I was just asked to run npm install and react start. This class is a couple years old so its been causing alot of dependency issues and other things I need to research on my own.

1 Answers

I would suggest familiarizing yourself with Promises and try/catch blocks.

Try/Catch - MDN Promise - MDN

They're essential components of javascript's asynchronous functionality. Here's an example based on your first route.

app.get('/users', async (req, res) => {
  try {
    const users = await User.find();
    res.json(users);
  } catch (err) {
    console.info("Error getting users", err.message)
  }
});

I'll let sources like MDN explain the technical aspects of async javascript more eloquently than I could. But at a high level, await before a function invocation is your giveaway here that the invoked function is asynchronous. Wrapping it in a try/catch block allows you to control what happens in case the operation throws an error, and so it won't crash your application.

Related