title: Check if email is in database in custom express-validator. (node, express, mysql)
body: <pre><code>//Update the user's email endpoint.
  apiRouter.post('/update-email', [
  check('newEmail')
      .isEmail().withMessage('Please Insert a valid Email')
      .custom(newEmail=&gt; {
          db.query(`SELECT user_id FROM users WHERE email = ?`, newEmail,(err, res)=&gt; {
              if(res.length &gt; 0) throw new Error('Email is already registered.');
          });
      })
  ], (req, res)=&gt; { 
      const errors = validationResult(req);
  if (!errors.isEmpty()) {
      return res.status(422).json(errors);
  } else {
      const newEmail = req.body.newEmail;
      const id = req.body.id;
      userCRUDfuncs.updateEmail(id, newEmail, db, (err=&gt; {
          if(!err) { 
              return res.status(201).send();
          } else {
              return res.status(404).send();
          }
      }));
  }
  })
  </code></pre>
  
  <p>This code returns the following error: "throw err; // Rethrow non-MySQL errors".</p>
  
  <p>I have tried using callbacks and Promises but I can never throw the error outside the query function. I could not find a way to signal the outside function to throw the error.
  I really appreciate your help on this .
  Thanks in advance.  </p>