In the provided code, the first promise is not waiting for findUser() to return before proceeding because:
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 } }); } }); }); }
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!