【问题标题】:node.js async getting data from dbnode.js 异步从数据库获取数据
【发布时间】:2021-03-18 01:33:49
【问题描述】:

我正在创建一个 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)
            }
        )
    }
};

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

我尝试过使用 Promise,但无法正确使用。 This 是我尝试做的。

我怎样才能做到这一点?

【问题讨论】:

  • 您能否编辑您的问题并向我们展示如何尝试使用 Promise?
  • @eol 我添加了显示如何使用承诺的链接。我删除了我使用的代码:(

标签: mysql node.js express promise


【解决方案1】:

您可以使用util.promisify 函数将callback 转换为promise,然后以async/await 的方式使用它。

这是代码示例:

我假设您使用mysql 包进行数据库连接和支持async/await 的NodeJS 版本:

const {promisify} = require('util');                                                                                    
const pool = require('../../config/db');                                                                                
                                                                                                                        
const getProductVariantsById = id => {                                                                                  
    return promisify(pool.query)('SELECT * FROM product_variants WHERE product_id = ?', [id]);                          
}                                                                                                                       
                                                                                                                        
const getProductById = async (id) => {                                                                                  
    const [products, variants] = await Promise.all([                                                                    
        // Assuming you're using 'mysql' package                                                                      
        promisify(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]),                                                                                     
        getProductVariantsById(id),                                                                                     
    ]);
    

    // Note: What if a products array is empty? you should handle this case too.                                                                                                         
                                                                                                                        
    const productObject = {                                                                                             
        id: products[0].id,                                                                                             
        name: products[0].name,                                                                                         
        description: products[0].description,                                                                           
        brand: {                                                                                                        
            id: products[0].brand_id,                                                                                   
            name: products[0].brand_name                                                                                
        }                                                                                                               
        variants, // ... or whatever you wanna do with this array                                                       
    };                                                                                                                  
}                                                                                                                       
                                                                                                                        
module.exports = {                                                                                                      
    getProductVariantsById,                                                                                             
    getProductById,                                                                                                     
}; 

...您还可以考虑通过将 JOIN 添加到 product_variants 表中来处理 SQL 查询中的所有这些逻辑

【讨论】:

    【解决方案2】:

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

    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();
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-04
      • 2015-01-30
      • 2020-07-14
      • 1970-01-01
      • 2020-06-01
      • 1970-01-01
      • 2015-06-20
      • 1970-01-01
      • 2019-04-25
      相关资源
      最近更新 更多