【发布时间】: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