Use Promises to Process MySQL Return Values in Node.js
Node.js's asynchronous nature poses challenges for developers accustomed to synchronous programming. This can be illustrated with a function like getLastRecord that fetches data from a MySQL function.
When attempting to return a value from getLastRecord, developers may encounter issues due to node's async nature. Here's how to address this using Promises:
<code class="javascript">function getLastRecord(name) { return new Promise((resolve, reject) => { const connection = getMySQL_connection(); const query_str = "SELECT name, " + "FROM records " + "WHERE (name = ?) " + "LIMIT 1 "; const query_var = [name]; connection.query(query_str, query_var, (err, rows, fields) => { if (err) { return reject(err); } resolve(rows); }); }); }</code>
To handle the returned value, you can use then and catch callbacks:
<code class="javascript">getLastRecord('name_record').then(function(rows) { // Processing of rows goes here }).catch((err) => { throw err; });</code>
Promises allow you to avoid callback nesting and improve code readability. They become particularly useful when combined with Promise.all and accumulators like Array.prototype.reduce.
The above is the detailed content of How can Promises be Used to Handle Asynchronous MySQL Results in Node.js?. For more information, please follow other related articles on the PHP Chinese website!