Promise and Connection Issues
In this Node.js code, a promise is expected to wait for the completion of the findUser function, which it does not. The issue stems from the asynchronous execution of database queries.
Connection Callback Function
Within findUser, a connection to the database is established using pool.getConnection. This function takes a callback function as an argument, which is called when the connection is ready. However, the code incorrectly returns data within this callback, leading to undefined being returned before the query is complete.
To address this, the findUser function should pass a callback to pool.getConnection that resolves or rejects a promise, indicating whether the query was successful or not.
Chaining Promises
The use of promises allows code to be executed sequentially. In the code provided, the first promise should be chained to the next promise using then instead of callback functions, as shown below:
promise.then(function(rows) { return new Promise(function (resolve, reject) { loginC.doSomething(data); if (success) { resolve(data); } else { reject(reason); } }); }, function(reason) { console.log("error handler second"); });
Error Handling
The reason the "error handler second" message is output is because an error occurs when the database connection fails. The error handling in the connection.on('error') event listener is not used correctly. This error propagates to the findUser function and is captured by the second error handler in the chaining.
The findUser function should reject the promise with the error message, which will then be propagated to the error handler in the promise chain.
The above is the detailed content of How Can I Chain Promises Correctly in Node.js When Working with Database Queries?. For more information, please follow other related articles on the PHP Chinese website!