gpt4 book ai didi

javascript - express 和 sequelize 将循环结构转换为 JSON

转载 作者:行者123 更新时间:2023-11-30 14:12:07 25 4
gpt4 key购买 nike

我有一个异步 Sequelize 函数

async getTrips() {
let trips = await Trip.findAll({
order: [['id']]
});

const data = trips.map(trip => ({
...trip,
milestones: async () => await Milestone.findAll({
where: {
trips_id: trip.id
}
}),
vendor_charges: async () => await VendorCharge.findAll({
where: {
trips_id: trip.id
}
}),
trip_notes: async () => await TripNote.findAll({
where: {
trips_id: trip.id
}
}),
pieces: async () => await Pieces.findAll({
where: {
trips_id: trip.id
}
})
}))
return data
}

然后在 express 路由器中运行

tripsRouter.get('/getAllTrips', (req, res) => {
const errors = validationResult(req)
if (!errors.isEmpty())
return res.status(422).json(errors.array())
tripsService.getTrips()
.then(trips =>
res.status(200).json({
exception: false,
payload: trips
})
);
})

这似乎在执行时产生“Converting circular structure to JSON”错误

这是错误堆栈:

(node:9322) UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON at JSON.stringify () at o.getTrips.then.e (/home/sandra/development/lakefrontcargo-v2/dist/index.js:1:57753) at (node:9322) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:9322) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. [nodemon] restarting due to changes...

最佳答案

由于 map 返回 promise 数组,所以我建议您使用 Promise.all 来等待所有 promise 完成。

const data  = Promise.all ( trips.map(trip => ({
...trip,
milestones: async () => await Milestone.findAll({
where: {
trips_id: trip.id
}
}),
vendor_charges: async () => await VendorCharge.findAll({
where: {
trips_id: trip.id
}
}),
trip_notes: async () => await TripNote.findAll({
where: {
trips_id: trip.id
}
}),
pieces: async () => await Pieces.findAll({
where: {
trips_id: trip.id
}
})
})) );


return await data;

关于javascript - express 和 sequelize 将循环结构转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54232872/

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