Javascript 如何将回调参数分配给全局变量?
我在mongodb数据库里有一些书。为了从控制台获取信息,我使用了:Javascript 如何将回调参数分配给全局变量?,javascript,node.js,mongodb,express,callback,Javascript,Node.js,Mongodb,Express,Callback,我在mongodb数据库里有一些书。为了从控制台获取信息,我使用了: Books.find().exec((reject,resolve)=>{ console.log(resolve) }) 然后我得到我的数组。虽然我想将数组分配给一个变量,并在浏览器中显示它,但我使用express、handlebar作为模板引擎和主体解析器。我已经尝试过传递其他信息(不是从数据库),一切都很好。但是,当我尝试时: let books; Books.find().exec((rej
Books.find().exec((reject,resolve)=>{
console.log(resolve)
})
然后我得到我的数组。虽然我想将数组分配给一个变量,并在浏览器中显示它,但我使用express、handlebar作为模板引擎和主体解析器。我已经尝试过传递其他信息(不是从数据库),一切都很好。但是,当我尝试时:
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});
});
});