undefined with async/await nodejs



我的代码正确返回对象,但当我试图从中获取值时,它返回未定义。到底是什么问题?

const Notification = require('../../../models/Notification');
module.exports = function onRouterload() {
return {
allRouter: async (req, res, next) => {
// for the admin layout
req.app.locals.layout = 'admin';
// load notification
async function notification() {
try {
const result = Notification.findAll({ where: { status: 'unread' } });
const data = await result;
return data;
} catch (error) {
console.log(error);
}
}
const notificationInfo = await notification();
// return undefined               
console.log(notificationInfo.status);
res.locals.notification = notificationInfo;
next();
},
};
};

findAll返回一个项目数组,因此notificationInfo包含一个数组,您应该遍历它以能够访问每个项目的status字段:

const notificationInfo = await notification();
for (const item of notificationInfo) {
console.log(item.status);
}

最新更新