Home > Database > Mysql Tutorial > body text

Why Is My Node.js Login API Not Working with Promises?

Patricia Arquette
Release: 2024-11-16 06:38:02
Original
632 people have browsed it

Why Is My Node.js Login API Not Working with Promises?

Node.js Express and Promises Not Behaving as Expected

Your Node.js login API is exhibiting unexpected behavior due to a misunderstanding of how promises interact with asynchronous operations. Let's address each issue:

1. Promise Not Waiting for Database Query

Your findUser() function is not returning a promise. Instead, it returns undefined immediately because the database query is asynchronous and takes time to execute. To fix this, you need to pass a callback function to the query() method, which will be invoked when the query completes:

me.findUser = function(params, res) {
  var username = params.username;

  return new Promise(function (resolve, reject) {
    pool.getConnection(function (err, connection) {
      if (err) {
        reject(err);
      } else {
        connection.query('select ...', [username], function (err, rows) {
          connection.release();
          if (!err) {
            resolve(rows);
          } else {
            reject(err);
          }
        });
      }
    });
  });
}
Copy after login

2. Error Handler Not Triggering

Your error handler is not triggered because the reject() method of the promise is never called. In your code, you return false from the callback for the database query when an error occurs. Instead, you should reject() the promise with the error:

me.findUser = function(params, res) {
  // ...

  return new Promise(function (resolve, reject) {
    // ...

    connection.query('...', [username], function (err, rows) {
      connection.release();
      if (!err) {
        resolve(rows);
      } else {
        reject(err);
      }
    });
  });
}
Copy after login

Revised Routes File

Here is a corrected version of your login route file that uses promises properly:

module.exports = function(app) {

  app.post('/login/', async function(req, res, next) {

    try {
      // Find user in database
      var rows = await loginM.findUser(req.body, res);

      // Do something with the data
      var result = await loginC.doSomething(rows);

      console.log("Success");
    } catch (err) {
      console.log("Failed: " + err.message);
    }
  });
}
Copy after login

Explanation

By using promises, you ensure that each step in your login API executes in sequence. The await keyword makes the code wait for the promise to resolve before proceeding, ensuring that the next step has access to the data from the previous step. Additionally, using try/catch allows you to handle any errors that may occur during the process.

The above is the detailed content of Why Is My Node.js Login API Not Working with Promises?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template