Home >Database >Mysql Tutorial >How to Efficiently Handle MySQL Return Values in Node.js Using Promises?
Using Promises to Handle MySQL Return Values in Node.js
In this asynchronous programming paradigm, handling MySQL return values requires a different approach compared to languages like Python. This article focuses on how to restructure code using promises to effectively process MySQL results.
Consider the following example:
<code class="javascript">function getLastRecord(name) { var connection = getMySQL_connection(); var query_str = "SELECT name, " + "FROM records " + "WHERE (name = ?) " + "LIMIT 1 "; var query_var = [name]; connection.query(query_str, query_var, function (err, rows, fields) { //if (err) throw err; if (err) { //throw err; console.log(err); logger.info(err); } else { //console.log(rows); return rows; } }); //var query = connection.query(query_str, function (err, rows, fields) { } var rows = getLastRecord('name_record'); console.log(rows);</code>
This code struggles due to the asynchronous nature of Node.js. To address this issue, we can adopt a promise-based solution:
<code class="javascript">function getLastRecord(name) { return new Promise(function (resolve, reject) { // The Promise constructor should catch any errors thrown on // this tick. Alternately, try/catch and reject(err) on catch. var connection = getMySQL_connection(); var query_str = "SELECT name, " + "FROM records " + "WHERE (name = ?) " + "LIMIT 1 "; var query_var = [name]; connection.query(query_str, query_var, function (err, rows, fields) { // Call reject on error states, // call resolve with results if (err) { return reject(err); } resolve(rows); }); }); }</code>
Now, we can process the return value using a then/catch block:
<code class="javascript">getLastRecord('name_record').then(function (rows) { // now you have your rows, you can see if there are <20 of them }).catch((err) => setImmediate(() => { throw err; })); // Throw async to escape the promise chain</code>
By embracing promises, we can handle MySQL return values more efficiently in Node.js, taking advantage of its asynchronous capabilities while maintaining readability.
The above is the detailed content of How to Efficiently Handle MySQL Return Values in Node.js Using Promises?. For more information, please follow other related articles on the PHP Chinese website!