germainelol germainelol - 1 month ago 6
Node.js Question

ESLint consistent-return and nested callbacks

I'm having some issues with the consistent-return rule provided by ESLint. The code below will throw a

consistent-return
warning for the
User.findOne
callback function. As far as I can tell, I can only run the
.remove
action if there is no
findErr
and if there is an
existingUser
.

What would be the best practice for avoiding these nested callbacks? I would like to pass the
consistent-return
warning, but haven't really seen any solutions online.

function remove(req, res) {
User.findOne({ username: req.params.username }, (findErr, existingUser) => {
if (findErr) return res.status(500).send(errorHandler.getErrorMessage(findErr));
if (!existingUser) return res.status(404).send({ message: 'User not found' });

existingUser.remove((removeErr) => {
if (removeErr) return res.status(500).send(errorHandler.getErrorMessage(removeErr));

return res.json({ message: `${existingUser.username} successfully deleted` });
});
});
}

Answer

What would be the best practice for avoiding these nested callbacks?

Promises.

I would like to pass the consistent-return warning

Then you'd best not use early-returns. Instead, write

function remove(req, res) {
  User.findOne({ username: req.params.username }, (findErr, existingUser) => {
    if (findErr) res.status(500).send(errorHandler.getErrorMessage(findErr));
    else if (!existingUser) res.status(404).send({ message: 'User not found' });

    else existingUser.remove((removeErr) => {
      if (removeErr) res.status(500).send(errorHandler.getErrorMessage(removeErr));

      else res.json({ message: `${existingUser.username} successfully deleted` });
    });
  });
}

Alternatively, you should be able to do

function remove(req, res) {
  User.findOne({ username: req.params.username }, (findErr, existingUser) => {
    if (findErr) {
      res.status(500).send(errorHandler.getErrorMessage(findErr));
      return;
    }
    if (!existingUser) {
      res.status(404).send({ message: 'User not found' });
      return;
    }
    existingUser.remove((removeErr) => {
      if (removeErr) {
        res.status(500).send(errorHandler.getErrorMessage(removeErr));
        return;
      }
      res.json({ message: `${existingUser.username} successfully deleted` });
    });
  });
}

You also could enable the { "treatUndefinedAsUnspecified": true } option and use return void ….