async/await nodejs 未定义
undefined with async/await nodejs
我的代码 return 对象正确,但是当我尝试从中获取值时,它 return 未定义。确切的问题是什么?
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 returns 一个项目数组,因此 notificationInfo
包含一个数组,您应该遍历它以便能够访问 status
每一项的字段:
const notificationInfo = await notification();
for (const item of notificationInfo) {
console.log(item.status);
}
我的代码 return 对象正确,但是当我尝试从中获取值时,它 return 未定义。确切的问题是什么?
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 returns 一个项目数组,因此 notificationInfo
包含一个数组,您应该遍历它以便能够访问 status
每一项的字段:
const notificationInfo = await notification();
for (const item of notificationInfo) {
console.log(item.status);
}