【问题标题】:Access the data of variable outside the function in NodeJS在NodeJS中访问函数外变量的数据
【发布时间】:2016-05-02 11:16:36
【问题描述】:

我试图在变量外部获取pend 变量的值并将其作为响应发送,但我将其作为undefined 获取。

app.post('/getData', function(req, res){               
     MongoClient.connect(url, function(err, db) {

            for(i=0;i<5;i++)
            {
                var array;
                var id = "4136354161ff135631";
                var cursor =db.collection('messages').find( { "_id": ObjectId(id) } );
                cursor.each(function(err, doc) {
                   assert.equal(err, null);
                   if (doc != null) {
                      pend=doc;             
                   }        
                });  

                 if(i === 5(length)){  // -----> response is sent once the loop get over
                   console.log(pend);
                   res.send(pend);
                   db.close();
                   }            
            }
    });
});

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    由于 for 循环是异步的,您希望在它被计算之前 pend ,请尝试以下操作:

    app.post('/getData', function(req, res){               
         MongoClient.connect(url, function(err, db) {
    
                for(i=0;i<5;i++)
                {
                    var array;
                    var id = "4136354161ff135631";
                    var cursor =db.collection('messages').find( { "_id": ObjectId(id) } );
                    cursor.each(function(err, doc) {
                       assert.equal(err, null);
                       if (doc != null) {
                          pend=doc;             
                       }   
    
                       if(i === 5){ 
                       console.log(pend);
                       res.send(pend);
                       db.close();
                       }        
                    });     
    
                }
    
    
        });
    });
    

    【讨论】:

    • 它没有发送响应,我想在 for 循环结束后发送响应。
    • 感谢 subburaj 的快速响应..但我正在尝试您的解决方案并生成响应。如果我在任何地方出错,请帮助我
    • 它在 res.send(); 的 if 条件下被击中;代码写好了
    • 是的,问题解决了,生成了响应,但存在数据库连接错误。即在获取 3 个 ids 数据后,它显示 mongodb 套接字已关闭..需要您的帮助..
    • 是的,感谢 subburaj 帮助我,这真的帮了我很多。再次非常感谢
    猜你喜欢
    • 1970-01-01
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多