如何将回调的参数分配给全局变量?
How to assign an argument of a callback to a global variable?
我在 mongodb 数据库中有一些书。为了从它获取信息到控制台,我使用了:
Books.find().exec((reject,resolve)=>{
console.log(resolve)
})
然后我得到我的数组。虽然,我想将数组分配给一个变量,并在浏览器中显示它,但我正在使用 express、handlebars 作为模板引擎和主体解析器。我已经尝试传递其他信息(不是来自数据库),一切正常。但是,当我尝试时:
let books;
Books.find().exec((reject,resolve)=>{
books = resolve
});
router.get('/',(req,res)=>{
res.render('index',{books:books});
});
nothing displays in the browser. Then I modified it a bit, and it I got the array, but I don't thing that's the right way of doing it.
Books.find().exec((reject,resolve)=>{
router.get('/',(req,res)=>{
res.render('index',{resolve:resolve});
});
});
你应该在请求函数中调用 Books.find()。
router.get('/',(req,res)=>{
Books.find().exec((reject,resolve)=>{
res.render('index',{books:resolve});
});
});
我在 mongodb 数据库中有一些书。为了从它获取信息到控制台,我使用了:
Books.find().exec((reject,resolve)=>{
console.log(resolve)
})
然后我得到我的数组。虽然,我想将数组分配给一个变量,并在浏览器中显示它,但我正在使用 express、handlebars 作为模板引擎和主体解析器。我已经尝试传递其他信息(不是来自数据库),一切正常。但是,当我尝试时:
let books;
Books.find().exec((reject,resolve)=>{
books = resolve
});
router.get('/',(req,res)=>{
res.render('index',{books:books});
});
nothing displays in the browser. Then I modified it a bit, and it I got the array, but I don't thing that's the right way of doing it.
Books.find().exec((reject,resolve)=>{
router.get('/',(req,res)=>{
res.render('index',{resolve:resolve});
});
});
你应该在请求函数中调用 Books.find()。
router.get('/',(req,res)=>{
Books.find().exec((reject,resolve)=>{
res.render('index',{books:resolve});
});
});