【问题标题】:undefined with async/await nodejs未使用 async/await nodejs 定义
【发布时间】:2021-10-05 23:50:04
【问题描述】:

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

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

【问题讨论】:

    标签: node.js express async-await middleware


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-09
      • 2021-02-17
      • 2020-06-06
      • 2017-07-13
      • 2021-10-21
      • 1970-01-01
      • 2019-12-18
      • 2021-06-15
      相关资源
      最近更新 更多