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条)

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?