2

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...

Sandra Willford
  • 3,459
  • 11
  • 49
  • 96
  • 1
    `findAll()` resolves with an array of `Model`s, not plain objects. These models have all sorts of internal properties and circular references, which cannot be turned into plain objects (via JSON) by express, when invoking `res.json()`. The solution is to strip those references away, for every `findAll()` call, like so`= (await Model.findAll()).map((entry) => entry.toJSON())` – Mihai Potra Jan 17 '19 at 09:57
  • Possible duplicate of [JSON.stringify, avoid TypeError: Converting circular structure to JSON](https://stackoverflow.com/questions/11616630/json-stringify-avoid-typeerror-converting-circular-structure-to-json) – bork Jan 17 '19 at 13:53
  • I havent messed with them in awhile but regarding circular serialization errors, Douglas Crockford has a solution and ResurectJS worked pretty well for me too – Marie Jan 17 '19 at 13:58

1 Answers1

2

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;
bereket gebredingle
  • 12,064
  • 3
  • 36
  • 47