douyakao5308 2015-01-05 18:00
浏览 44
已采纳

NodeJS同步调用

I am trying to fetch the number of records from Database using nodejs but the problem is that due to sync requests , I am not able to print them. When I try to print it inside the function , it prints fine but outside the function , it doesn't. I know it is due to sync behavior of JS but I want to do this (may be asynchronsly) . I am very new to Javascript and nodejs , so please guide me how can I do this. here is the code.

router.post('/numofrecs', function(req, res) {

        var db = new Db('nmydb', new Server('localhost', '27017'));
        db.open(function (err, db) {
        db.authenticate('', '', function (err, result) {


            var url = 'mongodb://localhost:27017/nmydb';
            client.connect(url, function (err, db) {
                que = new Array();
                var questioncol = db.collection('allquestions');
                questioncol.find({}).count(function (err, data) {
                    rec = data;
                    console.log("Num of rec:"+rec);
                    //inside the connect function , it prints fine here
                });

                console.log('Num of rec:'+ rec);


//but it doesnot print here outside the connect function and just print "undefined"
  • 写回答

2条回答 默认 最新

  • du9537 2015-01-05 18:23
    关注

    Since you are building an HTTP server, you do not want to have any synchronous actions on your server because such actions would result in your server becoming unresponsive to all clients during the synchronous action. Instead, you should do the work you need within the callback of the db query.

    router.post('/numofrecs', function(req, res) {
        var db = new Db('nmydb', new Server('localhost', '27017'));
        db.open(function (err, db) {
            db.authenticate('', '', function (err, result) {
                var url = 'mongodb://localhost:27017/nmydb';
                client.connect(url, function (err, db) {
                    var que = new Array();
                    var questioncol = db.collection('allquestions');
                    questioncol.find({}).count(function (err, data) {
                        console.log("Num of rec:"+data);
                        // do stuff with data here.
                        doStuff(data);
                    });
                });
            });
        });
    });
    

    Don't forget to var your variables.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像