Home > Database > Mysql Tutorial > body text

How to Handle MySQL Return Values Asynchronously in Node.js with Promises?

Barbara Streisand
Release: 2024-10-26 16:33:02
Original
180 people have browsed it

How to Handle MySQL Return Values Asynchronously in Node.js with Promises?

Leveraging Promises to Process MySQL Return Values in Node.js

In transitioning from Python to Node.js, the asynchronous nature of Node.js can present challenges. Consider a scenario where you need to return a value from a MySQL function, such as getLastRecord(name).

Traditionally, Node.js uses callbacks for asynchronous operations. However, to handle the asynchronous nature of getLastRecord(), we'll leverage Promises.

To implement the function using a Promise:

function getLastRecord(name) {
  return new Promise((resolve, reject) => {
    // Setup MySQL connection and query
    // ...

    connection.query(query_str, query_var, (err, rows, fields) => {
      if (err) {
        return reject(err); // Handle error
      }
      resolve(rows); // Resolve with results
    }); // Callback function
  });
}
Copy after login

To handle the returned value, you can chain .then() and .catch() callbacks to the Promise:

getLastRecord('name_record')
  .then((rows) => {
    // Handle returned rows here
    console.log(rows);
  })
  .catch((err) => {
    // Handle errors here
    console.log(err);
  });
Copy after login

You can also implement the conditional check:

getLastRecord('name_record')
  .then((rows) => {
    if (rows.length > 20) {
      console.log('action');
    }
  });
Copy after login

By adopting Promises in this scenario, you introduce a more structured and readable approach to handling asynchronous operations, ensuring a cleaner and more maintainable codebase.

The above is the detailed content of How to Handle MySQL Return Values Asynchronously in Node.js with Promises?. 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!