Home  >  Article  >  Database  >  How to Handle MySQL Return Values Asynchronously in Node.js with Promises?

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 16:33:02181browse

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
  });
}

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);
  });

You can also implement the conditional check:

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

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!

Statement:
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