![](/img/trans.png)
[英]Promises and Express 4.x - TypeError: Cannot read property “then” of undefined
[英]TypeError: Cannot read property 'then' of undefined using promises
我将这个网站作为一个项目,它是 AirBnB 的“沃尔玛”版本。
这是按钮应该为上下文执行的操作:
用户将单击列表上的“进行预订”按钮。 他们将选择开始和结束日期,然后提交。 这将向服务器发送 HTTP 请求。
但是,我遇到了返回的错误:
TypeError:无法读取 /vagrant/LightBnB/LightBnB_WEB_APP/server/apiRoutes.js:44:7 <--
第 44:7 行是下面的 API 路由:
这导致了错误:
.then((reservation) => {
res.send(reservation);
这是导致问题的 API ROUTE Logic:
router.post('/reservations', (req, res) => {
const userId = req.session.userId;
database
.addReservation({ ...req.body, guest_id: userId })
.then((reservation) => {
res.send(reservation);
})
.catch((e) => {
console.error(e);
res.send(e);
});
});
该路线正在调用函数 addReservation(),如下所示:
/**
* Add a reservation to the database
* @param {{}} reservation An object containing all of the reservation details.
* @return {Promise<{}>} A promise to the reservation.
*/
const addReservation = function (reservation) {
const queryString = `
INSERT INTO reservations(
start_date,
end_date,
property_id,
guest_id
)
VALUES ($1, $2, $3, $4)
RETURNING *
`;
const values = [
reservation.start_date,
reservation.end_date,
reservation.property_id,
reservation.guest_id,
];
pool
.query(queryString, values)
.then((res) => {
res.rows;
})
.catch((e) => console.log(e.message));
};
exports.addReservation = addReservation;
如果您需要更多信息,请告诉我。
TypeError:无法读取未定义的属性“then”
addReservation()
没有返回值,因此它返回undefined
。 因此,当您尝试执行addReservation(...).then(...)
时,您最终会尝试在undefined
上访问.then()
,这会导致您得到错误。
在addReservation()
内部,您需要更改:
pool.query(...).then(...).catch(...)
至
return pool.query(...).then(...).catch(...)
这将返回您的承诺,以便调用者可以在返回的承诺上使用.then()
。
请注意,您在 addReservation() 中的addReservation()
.catch()
处理程序正在记录,然后“吃掉”错误。 您可能应该重新抛出错误,以便调用者可以看到错误:
改变这个:
.catch((e) => console.log(e.message));
对此:
.catch((e) => {
console.log(e.message)
// re-throw the error so it propagates to the caller
throw e;
});
另外,请注意res.send(e)
可能不会提供太多有用的信息,因为 Error 对象的大多数属性是不可枚举的,因此当res.send()
将 Error 对象转换为 JSON 时不会显示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.