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

时间:2017-12-20 07:43:37

标签: node.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;
    }
});

});

1 个答案:

答案 0 :(得分:1)

这里使用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