我有一个异步 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
}
然后在快速路由器中运行
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
})
);
})
执行时似乎会产生“将循环结构转换为 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/