Reputation: 3789
I have an async Sequelize funcion
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
}
that then runs in the express router
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
})
);
})
this seems to be producing a "Converting circular structure to JSON" error when it's exectuted
this is the error stack:
(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...
Upvotes: 2
Views: 4851
Reputation: 13006
Since map
returns array of promises so I suggest you use Promise.all
for waiting all the promises to finish.
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;
Upvotes: 2