Home > Database > Mysql Tutorial > body text

How can Promises be Used to Handle Asynchronous MySQL Results in Node.js?

Linda Hamilton
Release: 2024-10-27 03:43:03
Original
579 people have browsed it

How can Promises be Used to Handle Asynchronous MySQL Results in Node.js?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!