首页  >  文章  >  数据库  >  如何在 Node.js 中使用 Promises 异步处理 MySQL 返回值?

如何在 Node.js 中使用 Promises 异步处理 MySQL 返回值?

Barbara Streisand
Barbara Streisand原创
2024-10-26 16:33:02181浏览

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

在 Node.js 中利用 Promise 处理 MySQL 返回值

从 Python 过渡到 Node.js,Node.js 的异步特性。 Node.js 可能会带来挑战。考虑一个场景,您需要从 MySQL 函数返回一个值,例如 getLastRecord(name)。

传统上,Node.js 使用回调进行异步操作。但是,为了处理 getLastRecord() 的异步特性,我们将利用 Promise。

要使用 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
  });
}

要处理返回值,您可以链接Promise 的 .then() 和 .catch() 回调:

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

您还可以实现条件检查:

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

通过在这种情况下采用 Promise,您引入了更加结构化和可读的方法来处理异步操作,确保更干净和更可维护的代码库。

以上是如何在 Node.js 中使用 Promises 异步处理 MySQL 返回值?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn