In your provided code, the promise is not pausing the execution of the code to wait for the findUser function to complete. This is because the findUser function is not returning a promise. Instead, it returns undefined immediately, causing the code to proceed without waiting for the database query to finish.
To fix this, the findUser function should return a promise that resolves with the rows retrieved from the database:
me.findUser = function(params, res) { var username = params.username; return new Promise(function (res, rej) { pool.getConnection(function (err, connection) { if (err) { rej('db error'); } else { connection.query('SELECT Id, Name, Password FROM Users WHERE Users.Name = ?', [username], function (err, rows) { connection.release(); if (!err) { res(rows); } else { rej('other error'); } }); } }); }); }
With this change, the promise will pause the execution of the code and wait for the query to complete before proceeding with the if/else statement.
The error handler error handler second is outputted because the findUser function rejects the promise with an error message. This causes the then handler to be skipped, and the catch handler (with the message 'error handler second') to be invoked instead.
To resolve this, ensure that the findUser function handles errors and resolves with the desired data correctly. Additionally, you can add error handling to the next level of the promise chain to handle any subsequent errors.
The above is the detailed content of Why Is My Promise in Node.js Express Not Waiting for the Database Query to Complete?. For more information, please follow other related articles on the PHP Chinese website!