Home > Database > Mysql Tutorial > body text

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

Susan Sarandon
Release: 2024-10-25 17:28:02
Original
827 people have browsed it

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

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

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!

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!