Home >Database >Mysql Tutorial >Why is the Second Promise Error Handler Executed Before the First Promise's 'Failed' Output?

Why is the Second Promise Error Handler Executed Before the First Promise's 'Failed' Output?

Linda Hamilton
Linda HamiltonOriginal
2024-11-14 09:45:02752browse

Why is the Second Promise Error Handler Executed Before the First Promise's

Node.js Express and Promises Not Behaving as Expected

First Promise Not Waiting for findUser() Completion

In the provided code, the first promise is not waiting for findUser() to return before proceeding because:

  • .findUser() asynchronously queries the database using a callback function.
  • The callback is not used to resolve the promise. Instead, the promise is resolved with rows, which is undefined at the time of the promise creation.

Solution:

Wrap the database query in a function that returns a promise and resolve the promise with the query result:

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

    return new Promise(function (resolve, reject) {
        pool.getConnection(function (err, connection) {
            console.log("Connection ");

            if (err) {
                console.log("ERROR 1 ");
                res.send({"code": 100, "status": "Error in connection database"});
                reject(err); // Reject the promise with the error
            } else {
                connection.query('select Id, Name, Password from Users ' +
                    'where Users.Name = ?', [username], function (err, rows) {
                    connection.release();
                    if (!err) {
                        resolve(rows); // Resolve the promise with the query result
                    } else {
                        reject(err); // Reject the promise with the error
                    }
                });
            }
        });
    });
}

Why error handler second is Outputted Instead of Failed

The error handler for the second promise is called because the first promise is rejected. However, the console.log("Failed"); line in the error handler is not executed because an error is thrown inside the .then() block.

To correctly handle the rejection of the first promise, use .catch() instead of .then():

promise.then(function(data) {
    return new Promise(...);
}, function (reason) {
    console.log("Failed");
});

The above is the detailed content of Why is the Second Promise Error Handler Executed Before the First Promise's 'Failed' Output?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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