Home >Database >Mysql Tutorial >Why Is My Node.js Login API Not Working with Promises?
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:
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); } }); } }); }); }
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); } }); }); }
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); } }); }
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!