Search code examples
node.jsexpressasync-awaitmiddleware

undefined with async/await nodejs


My code return the object properly but when I try to get value from it, then it return undefined. What is the exact issue ?

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();
                    },
                };
            };

Solution

  • findAll returns an array of items so notificationInfo contains an array and you should iterate through it to be able to access the status field of each item:

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