weixin_33736832 2018-03-17 19:21 采纳率: 0%
浏览 48

快递路线

Its possible to force a route ?

Example:

I have this route A:

notiSchema = notification model

router.get('/set', function(req, res){
    User.findById("userId". function(err, foundUser){
        foundUser.notiSchemaSent.forEach(function(notiSchema, i){
            if(req.user.notifications.length === 0){
                req.user.notifications.unshift(notiSchema);
                req.user.save();
            } else {
                req.user.notifications.forEach(function(userSchema, i){
                    if(req.user.notifications.indexOf(notiSchema) === -1){
                         req.user.notifications.unshift(notiSchema);
                         req.user.save();
                    }
                });
            }
        });
    });

    res.json(req.user.notifications);
});

Problem here is that the 'res.json' line is read before the userB is updated

So i created this other route B:

router.get('/get', middleware.isLoggedIn, function(req, res){
  res.json(req.user.notifications);
});

My Ajax:

$.get('/set', function(data){
    // I only add a "fa-spin" class here
}).then(function(){
    $.get('/get', function(data){
        $(data).each(function(i, item){
            $('.notDrop').prepend(item);
        });

        // Remove the "fa-spin" class
    });
}); 

But sometimes route "B" is called before "A" ends;

So i want to know if its possible to call the "B" route only after the "A" one gets totally finished.

  • 写回答

1条回答 默认 最新

  • weixin_33749242 2018-03-17 20:57
    关注

    I rewrote your route to accumulate all the changes into req.user.notifications and then just save once at the end (if the array was modified). This allows you to then have only one .save() operation and to know when it's done by passing a callback to it.

    Summary of changes:

    1. Accumulate results in the array and only save at the end.
    2. Only save if the array was modified.
    3. Get rid of the special case for .length === 0 as that is not needed.
    4. Use a callback on req.user.save() to know when it's done so we can then. send the response after the save is done.
    5. Add error handling for .save().
    6. Add error handling for .findById()

    Here's the code:

    router.get('/set', function(req, res){
        User.findById("userId", function(err, foundUser){
            if (err) {
               console.log(err);
               res.status(500).send("Error finding user.")
               return;
            }
            let origLength = req.user.notifications.length;
            foundUser.notiSchemaSent.forEach(function(notiSchema, i){
                req.user.notifications.forEach(function(userSchema, i){
                    if(req.user.notifications.indexOf(notiSchema) === -1){
                        req.user.notifications.unshift(notiSchema);
                    }
                });
            });
            if (req.user.notifications.length !== origLength) {
                req.user.save(function(err) {
                    if (err) {
                        console.log(err);
                        res.status(500).send("Error saving user notifications.")
                    } else {
                        res.json(req.user.notifications);
                    }
                });
            } else {
                res.json(req.user.notifications);
            }
        });
    });
    

    If you change your db code so you get an array of users from the find operation, then you can process those like this:

    router.get('/set', function(req, res){
        User.find({_id: {$in: arrayOfIds}}, function(err, foundUsers){
            if (err) {
               console.log(err);
               res.status(500).send("Error finding user.")
               return;
            }
            let origLength = req.user.notifications.length;
            foundUsers.forEach(function(foundUser) {
                foundUser.notiSchemaSent.forEach(function(notiSchema, i){
                    req.user.notifications.forEach(function(userSchema, i){
                        if(req.user.notifications.indexOf(notiSchema) === -1){
                            req.user.notifications.unshift(notiSchema);
                        }
                    });
                });
            });
            if (req.user.notifications.length !== origLength) {
                req.user.save(function(err) {
                    if (err) {
                        console.log(err);
                        res.status(500).send("Error saving user notifications.")
                    } else {
                        res.json(req.user.notifications);
                    }
                });
            } else {
                res.json(req.user.notifications);
            }
        });
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 大家帮我看看为什么错了
  • ¥15 unity互动琴弦抖动效果
  • ¥15 做了个的二极管反向饱和电流测量电路,但是测试达不到效果
  • ¥15 nginx无证书访问https失败
  • ¥15 树莓派启动AP热点传入数据
  • ¥15 multisim中关于74ls192n和DSWPK开关的问题(相关搜索:计数器)
  • ¥15 在误装Windows server2019 后如何利用Windows.old恢复?
  • ¥20 代码实现状态连接包过滤防火墙的设计与实现
  • ¥15 vscode的红色箭头爆红和has no default export报错
  • ¥15 关于#sql#的问题:#情况描述 在用vs对项目进行调试时,出现找不到网络路径,然后查看SQL配置工具,发现SQL服务显示远程调用过程失败(相关搜索:防火墙)