Home >Database >Mysql Tutorial >Why Does My Promise Resolve Prematurely in Node.js with Express and Promises?
In your code, the promise created for the findUser function executes immediately, but the function itself is asynchronous. Hence, the promise resolves prematurely before findUser can retrieve data.
Modify your findUser function to return a promise instead of attempting to return values synchronously. Here's an example:
me.findUser = function(params, res) { var username = params.username; return new Promise(function (resolve, reject) { pool.getConnection(function (err, connection) { if (err) { reject(err); return; } connection.query('select Id, Name, Password from Users ' + 'where Users.Name = ?', [username], function (err, rows) { connection.release(); if (err) { reject(err); } else { resolve(rows); } }); }); }); }
The "error handler second" message appears because the error handler in the second promise is rejected when findUser encounters an error. To fix this, modify the code as follows:
promise.then(function(data) { return new Promise(function (resolve, reject) { loginC.doSomething(data); if (success) { console.log("Success 2"); resolve(data); } else { console.log("Failed 2"); reject("Error in doSomething"); } }); }).catch(function (reason) { console.log("Error in findUser: " + reason); });
The above is the detailed content of Why Does My Promise Resolve Prematurely in Node.js with Express and Promises?. For more information, please follow other related articles on the PHP Chinese website!