node.js - 为什么第二个 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) 首先运行,因此返回未定义。为什么会这样?
解决方案
您提供的回调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});
}
});
}
});
})
推荐阅读
- postgresql-9.3 - PostgreSQL - 通过 regexp_replace 函数更新自己字段中的数据
- python - 源 HTML 不可预测 - Python Scrapy
- android - 如何在 Android Compose 的 AndroidView 中动态更新 RecyclerView
- python - 在 matplotlib 中绘制 y=times(作为数据)与 x=dates:如何格式化所有日期的 y 轴?
- angular-cli - 'compilation' 参数必须是 Compilation 的一个实例
- reactjs - React - 将答案显示为列表
- html - 使用社交媒体共享链接可缩短 URL
- svg - svg 文件作为“application/octet-stream”而不是“image/svg+xml”上传
- python - 为什么 Python 的“\x1B[1A”不能在 Google Colab 中工作?它适用于我的其他调试器
- r - 在 PC 上未安装 LaTeX 的情况下从 RMarkdown 创建 TeX 文件