首页 > 解决方案 > 为什么第二个 console.log 先运行?

问题描述

app.use(bodyParser.urlencoded({extended:true}))
mongoose.connect("mongodb://localhost:27017/shopDB",{useNewUrlParser:true,useUnifiedTopology: true});

app.get("/",function(req,res){
   var dbcollections;
   mongoose.connection.db.listCollections().toArray(function(err,names){
      if(err){
         console.log(err)
      }else{
         dbcollections = names;
         console.log(dbcollections) // first
      }
   });
   console.log(dbcollections) // second
   Item.find({},function(err,docs){
      if(err){
         console.log(err)
      }else{
        
        res.render("index", {list: docs ,collections: dbcollections});
      }
   }); 
   
})

控制台打印如下:

undefined
[
  {
    name: 'items',
    type: 'collection',
    options: {},
    info: { readOnly: false, uuid: [Binary] },
    idIndex: { v: 2, key: [Object], name: '_id_' }
  }
]

似乎第二个 console.log(dbcollections) 首先运行,因此返回未定义。为什么会这样?

标签: node.jsmongodbmongoose

解决方案


您提供的回调toArray()直到稍后才会执行。因此,您必须包含使用dbcollections该回调内部的代码。

app.use(bodyParser.urlencoded({extended:true}))
mongoose.connect("mongodb://localhost:27017/shopDB",{useNewUrlParser:true,useUnifiedTopology: true});

app.get("/",function(req,res){
   var dbcollections;
   mongoose.connection.db.listCollections().toArray(function(err,names){
      if(err){
         console.log(err)
      }else{
         dbcollections = names;
         console.log(dbcollections) // first
         
          Item.find({},function(err,docs){
            if(err){
               console.log(err)
            }else{

              res.render("index", {list: docs ,collections: dbcollections});
            }
         }); 
      }
   });
   
})



推荐阅读