代码之家  ›  专栏  ›  技术社区  ›  Sandra Willford

将循环结构转换为JSON的表达式和Sequalize

  •  0
  • Sandra Willford  · 技术社区  · 6 年前

    我有一个异步顺序函数

    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)UnhandlePromiseRejection警告:类型错误:将循环结构转换为JSON 在json.stringify()上 在o.gettrips.then.e(/home/sandra/development/lakefrontcargo-v2/dist/index.js:1:57753) 在 (节点:9322)UnhandlePromiseRejectionWarning:未处理的承诺拒绝。此错误是通过在不带catch块的异步函数内部引发的,或者通过拒绝未用.catch()处理的承诺而产生的。(拒绝ID:1) (节点:9322)[DEP0018]拒绝警告:不推荐使用未经处理的承诺拒绝。将来,未处理的Promise拒绝将使用非零退出代码终止node.js进程。 [nodemon]由于更改正在重新启动…

    1 回复  |  直到 6 年前
        1
  •  1
  •   bereket gebredingle    6 年前

    自从 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;
    
    推荐文章