提问者:小点点

使用promise从express中间件返回并从循环跳出返回404


我正在尝试使用下面与stolenCarDb对象一起使用的数据库函数从express返回一个对象(car)数组,但是数据库函数的功能非常良好

执行下面的操作将返回一个404,其中包含错误UnhandledPromiserEjectionWarning:error[ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端之后无法设置标头

router.post("/reportstolen", function (request: express.Request, response: express.Response, next: (err?: Error) => void) {
    stolenCarDb.put_car(request.body)
        .then(() => {
            stolenCarDb.get_available_cops()
                .then(cops => {
                    cops.forEach(cop => {
                        stolenCarDb.assign_cop_car(cop._id, request.body._id)
                            .then(() => response.status(201).send(`assgined cop ${cop._id} to car`))
                    })
                })
                .then(() => response.status(201).send("created"))
        })
        .catch(() => response.status(500).send("error"))
        .finally(next)
})

共1个答案

匿名用户

您正在多次向用户发送响应,这是您无法做到的。 在所有操作完成后,您应该只发送一次响应。