gpt4 book ai didi

node.js - 嵌套循环续写 Node.js 中的每条记录

转载 作者:行者123 更新时间:2023-12-03 22:19:32 24 4
gpt4 key购买 nike

我正在开发 API 以接收每个订单的订单项目。我无法收到订单商品的详细信息。请看下面的代码。

Controller.orderLists = (req, res, next) => {
--- some code ---
Model.Orders.findAll({
attributes: [
'order_id',
'status'
],
where: {
customer_id: req.customer_id,
status: 1
}
group: ['orders.order_id'],
limit: 1,
subQuery: false
}).then((orderList) => {
if (!_.isEmpty(orderList)) {
var results = [];
var index = 0;
orderList.forEach(function (order) {
getOrderInfo(order.order_id, function (err, items) {
console.log(items);
results[index] = {
'order_id': order.order_id,
'status': order.status,
'order_item': items
};

index++;
return results;
});
});

res.json({
status: 1,
msg: 'Order Lists',
data: results
});
} else {
res.json({
status: 1,
msg: 'Order not found',
data: results
});
}
}).catch((err) => {
console.error('ERROR :', err);
res.json({
status: -1,
msg: 'An error occured'
});
});
});

从模型中,我得到了订单 ID 列表。从列表中将运行每个订单以检索订单项目。我已经尝试了很多尝试代码,但看起来没有运气。
function getOrderInfo(order_id, callback) {
--- 1st attempt code ---
return Model.OrderItem.find({
attributes: [
[Sequelize.literal('sum(quantity)'), 'total_quantity']
],
where: {
order_id: order_id
}
}).then((order_data) => {
callback(null, JSON.stringify(order_data.dataValues));
});
--- end 1st attempt code ---

--- 2nd attempt code ---
return Sequelize.model('order_items').findOne({
attributes: [
[Sequelize.literal('sum(quantity)'), 'total_quantity']
],
where: {
order_id: order_id
}
}).then((data) => {
return callback(null, data.dataValues);
});
--- end 2nd attempt code ---

--- 3rd attempt code ---
var sql = "SELECT SUM(quantity) AS total_quantity FROM order_items WHERE order_id = " + order_id;
Sequelize.query(sql, {
plain: true,
type: Sequelize.QueryTypes.SELECT
}).then((order) => {
callback(null, order);
});
--- end 3rd attempt ---
}

当前和预期的结果:
Current: 
{
"status": 1,
"msg": "Order Lists",
"data": []
}

Expected:
{
"status": 1,
"msg": "Order Lists",
"data": [
{
"order_id": 1234,
"status": 1,
"order_item": {
"total_quantity": "3"
}
},{
--- some data ---
}
]
}

预期数据应来自结果变量。
日志显示了一些关于 promise 的警告。
0|AppServer:  | 2020-05-14 14:12:09 +08:00: (node:4740) Warning: a promise was created in a handler but was not returned from it
0|AppServer: | 2020-05-14 14:12:09 +08:00: at Function.Promise.attempt.Promise.try (c:\xampp\htdocs\api\node_modules\bluebird\js\release\method.js:29:9)

我认为 async 和 await 脚本可能有问题。如何让脚本保持并让 getOrderInfo() 先执行然后继续下一步?

请我需要帮助。谢谢

最佳答案

getOrderInfo 异步操作并返回一个 promise 。由于您不等待它,res.json(...) 在 promise 解决之前执行。您可以通过等待所有 promise 并在 then 处理程序中发送响应来修复:

...
const orderPromises = [];
orderList.forEach(function (order) {
orderPromises.push(getOrderInfo(order.order_id));
});

Promise.all(orderPromises)
.then(results => {
res.json({
status: 1,
msg: 'Order Lists',
data: results
});
});
...

function getOrderInfo(order_id) {
return Model.OrderItem.findOne({
attributes: [
[Sequelize.literal('sum(quantity)'), 'total_quantity']
],
where: {
order_id: order_id
}
})
.then(order => {
return {
'order_id': order.order_id,
'status': order.status,
'order_item': items
}
})
}

请注意,我建议使用 async/await 而不是纯 promise,因为它极大地提高了代码的可读性 -> 检查 this 以获取更多信息。

关于node.js - 嵌套循环续写 Node.js 中的每条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61790778/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com