Javascript 特快专递及;sequalize将循环结构转换为JSON
我有一个异步Sequelize函数Javascript 特快专递及;sequalize将循环结构转换为JSON,javascript,node.js,express,sequelize.js,Javascript,Node.js,Express,Sequelize.js,我有一个异步Sequelize函数 async getTrips() { let trips = await Trip.findAll({ order: [['id']] }); const data = trips.map(trip => ({ ...trip, milestones: async () => await Milestone.findAll({ where: {
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”错误
这是错误堆栈:
(节点:9322)未处理的PromisejectionWarning:TypeError:将循环结构转换为JSON
在JSON.stringify()上
在o.getTrips.then.e(/home/sandra/development/lakefrontcargo-v2/dist/index.js:1:57753)
在
(节点:9322)未处理的PromisejectionWarning:未处理的承诺拒绝。此错误源于在没有catch块的异步函数中抛出,或者拒绝未使用.catch()处理的承诺。(拒绝id:1)
(节点:9322)[DEP0018]弃用警告:未处理的承诺拒绝已弃用。将来,未处理的承诺拒绝将使用非零退出代码终止Node.js进程。
[nodemon]由于更改而重新启动
由于
map
返回承诺数组,因此我建议您使用Promise.all
等待所有承诺完成
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;
findAll()。这些模型具有各种内部属性和循环引用,当调用res.JSON()
时,express无法将它们转换为普通对象(通过JSON)。解决方案是去除那些引用,对于每个findAll()
调用,比如=(wait Model.findAll()).map((entry)=>entry.toJSON())
可能的重复,我已经有一段时间没有弄乱它们了,但是关于循环序列化错误,Douglas Crockford有一个解决方案,ResurectJS对我来说也很好