mysql - Node.js 异步从数据库获取数据

标签 mysql node.js express promise

我正在创建一个 API,它可以在一个 json 对象中获取产品对象以及该产品的变体。

我正在使用此代码来获取产品:

const pool = require("../../config/db");

module.exports = {
    getProductById: (id, callBack) => {
        pool.query(
            `SELECT
                p.id,
                p.name,
                p.description,
                b.id as brand_id,
                b.name as brand_name
            FROM product p
            INNER JOIN brand b ON p.brand_id = b.id
            WHERE p.id = ?`,
            [
                id
            ],
            (error, results, fields) => {
                if (error) {
                    return callBack(error);
                }

                // This is where I would like to call the getProductById
                // function so that I can add the array to the below          
                // productObject

                var productObject = {
                    id: results[0].id,
                    name: results[0].name,
                    description: results[0].description,
                    brand: {
                        id: results[0].brand_id,
                        name: results[0].brand_name
                    }
                };

                return callBack(null, productObject)
            }
        )
    }
};

我想从我已经创建的 api 函数中获取产品变体,如下所示:

const pool = require("../../config/db");

module.exports = {
    getProductVariantsById: (id, callBack) => {
        pool.query(
            `SELECT *
            FROM product_variants
            WHERE product_id = ?`,
            [
                id
            ],
            (error, results, fields) => {
                if (error) {
                    return callBack(error);
                }

                return callBack(null, productObject)
            }
        )
    }
};

我正在努力在 getProductVariantsById 函数中异步调用 getProductVariantsById 函数。

我尝试过使用 promise ,但我无法做到正确。 This这就是我试图做的。

我怎样才能实现这个目标?

最佳答案

如果你的 pool.query 是异步的,你可以使用 wait 运行

getProductById: async (id, callBack) => {
  ...
  await getProductVariantsById(id, callback);
}
getProductVariantsById: async (id, callBack) => {
  ...        
  await pool.query(...);
  ...
}

如果不是异步,要使用 Promise,你需要像这样的 smt

getProductVariantsById: async (id, callBack) => {
  return new Promise((resolve) => {
    pool.query(..)
    ...
    resolve();
  }
}

关于mysql - Node.js 异步从数据库获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65169965/

相关文章:

ajax - 将 View 渲染到 ExpressJS 中的变量中(用于 AJAX 响应)

node.js - @types/express 中是否有用于 Express 中间件功能的类型

php - 查找时间字符串大于当前时间 SQL 的行

javascript - 使用 node.js api 递归地监视目录

node.js - 如何在 Linux 上的 npm 上修复连接 ENETUNREACH

android - “Ionic cordova build android”错误

node.js - 在 Node express 中再次调用相同的请求

Mysql - 使用临时;使用文件排序

mysql - InnoDB 中 MyISAM 的 key_buffer_size 是多少?

PHP mysqli_query 不会执行