Home > Database > Mysql Tutorial > Why Is My Promise in Node.js Express Not Waiting for the Database Query to Complete?

Why Is My Promise in Node.js Express Not Waiting for the Database Query to Complete?

DDD
Release: 2024-11-19 02:22:02
Original
944 people have browsed it

Why Is My Promise in Node.js Express Not Waiting for the Database Query to Complete?

Promises Not Behaving as Expected in Node.js Express

Understanding the Issue

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.

Correcting the Code

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');
                    }
                });
            }
        });
    });
}
Copy after login

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.

Explaining the Error Handler

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template