”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何在 Node.js 中使用 Promises 异步处理 MySQL 返回值?

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

发布于2024-11-09
浏览:423

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

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

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

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

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

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

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,您可以引入一种更加结构化和可读的方法来处理异步操作,从而确保代码库更干净、更易于维护。

最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3