最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

在获取db响应中的数据之前,由节点js发送

运维笔记admin9浏览0评论

在获取db响应中的数据之前,由节点js发送

在获取db响应中的数据之前,由节点js发送

这是我设置的通知对象

  var sentNotificationObj = function (notification, eventid, addedorganizerpropic) {
        this.notification = notification;
        this.eventid = eventid;
        this.addedorganizerpropic = addedorganizerpropic;
    }

这是我的数组,它存储了通知对象

var notificationSetArray2 = [];

这是我的关于getnotification的api

router.post('/getnotification', function (req, res) {
    console.log('in aside');
    var id = req.body.userid;
    console.log('pos id' + id);
    User.findById({ _id: id }, function (err, result) {
        if (err) {
            console.log('err get notification');
            res.statusCode = 500;
            res.json({
                success: false,
                message: "severe error"
            });
        } else {

这是在数据库中获取数据的代码

for (var i = 0; i < result.notification.length; i++) {
    var addedevent = result.notification[i].addedevent;
    var notification = result.notification[i].notification;
    console.log('added event' + addedevent);
    console.log('added noti' + notification);
    User.findById({ _id: result.notification[i].addedorganizer }, function (err, addedorganizer) {
        if (err) {
            console.log('error get added user pofile pic');
        } else {

将图像转换为base64

            var base64str = base64_encode(addedorganizer.profileData.profileurl);
            console.log(base64str);
            console.log(notification);
            console.log(addedevent);
            var newsentNotificationObj = new sentNotificationObj(notification, addedevent, base64str);
            notificationSetArray2.push(newsentNotificationObj);
            console.log('succe get added user profile pic');
        }
    });
}

这是回应

        res.statusCode = 200;
            res.json({
                success: true,
                notificationArray: notificationSetArray2
            })
            console.log(notificationSetArray2);
            notificationSetArray2.length = 0;
    }
});

});

回答如下:

这里最简单的解决方案是在这里使用async库。 Node以异步方式运行代码。因此,在从数据库中获取任何数据之前发送响应是很自然的。

通过使用async,您可以按顺序执行此操作。所以它会被解决。使用async.series方法来解决这个问题。例如

async.series(
    [
        function(callback){
            // fetch your data here using mongo with your loop
            //
            //
            callback(); // this will trigger next step (call this after you finished iterating array)
        },
        function(callback){
            // after above code has been executed
            // send response here
            callback() // call this to proceed
        }
    ],

    function(err){
        // handle any error in here
    }
)

A good example of how to use asyncjs in node

发布评论

评论列表(0)

  1. 暂无评论