我有一个异步后缀功能
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) UnhandledPromiseRejectionWarning: TypeError:将循环结构转换为JSON.stringify () at JSON.stringify() at o.getTrips.subthe.e JSON.stringify(节点:9322) UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误起源于在异步函数中抛出而不带catch块,或者拒绝使用.catch()处理的承诺。(拒绝id: 1) (节点:9322) DEP0018 DeprecationWarning:未处理的承诺拒绝被取消。在未来,承诺不处理的拒绝将使用非零退出代码终止Node.js进程。没有恶魔因为改变而重新开始。
发布于 2019-01-17 05:51:04
因为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;
https://stackoverflow.com/questions/54232872
复制