Home  >  Article  >  Database  >  How to Convert Asynchronous MySQL Operations to Promises in Node.js?

How to Convert Asynchronous MySQL Operations to Promises in Node.js?

Susan Sarandon
Susan SarandonOriginal
2024-10-25 17:28:02828browse

How to Convert Asynchronous MySQL Operations to Promises in Node.js?

Converting Asynchronous MySQL Operations to Promises in Node.js

Node.js's asynchronous nature poses a challenge for developers coming from Python. To address this, this code snippet attempts to wrap a MySQL operation inside an asynchronous function that returns a value. However, this approach won't work due to the asynchronous nature of Node.js.

To resolve this issue, the operation needs to be refactored to return a promise. Using Bluebird, this can be achieved as follows:

<code class="javascript">function getLastRecord(name) {
  return new Promise((resolve, reject) => {
    // Establish a connection to MySQL
    const connection = getMySQL_connection();

    // Construct and execute the MySQL query
    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>

Now, you can handle the returned rows as desired:

<code class="javascript">getLastRecord('name_record').then((rows) => {
  // Access the rows and perform operations

  if (rows.length > 20) {
    console.log("action");
  }
}).catch((err) => {
  // Handle any errors
  setImmediate(() => { throw err; });
});</code>

This approach ensures that the operation is executed asynchronously, while allowing you to handle the returned value in a synchronous manner using promises.

The above is the detailed content of How to Convert Asynchronous MySQL Operations to Promises in Node.js?. 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