[英]Mongoose function logs correct data but using async function to get it returns undefined
我正在嘗試從數據庫查詢一些數據並將其返回給函數。 我遇到的問題是,當我記錄來自查詢的結果時,它正在運行,但是當我嘗試查詢該函數返回的內容時,卻變得不確定。 可能是我的貓鼬異步功能未正確設置。 或者,也許我只是對異步編程有一個錯誤的想法,因為我是異步編程的新手。
async function returnBlogThumbnails(filter = "recent", callback){
console.log("returning blogs")
//For now simply filter by most recent
if(filter === "recent"){
Blog.find({}).sort('-date').exec((err,docs) => {
return docs;
});
}
}
和調用此函數的函數
app.get('/', (req, res)=> {
console.log("go home");
//Call out to query the database then use async function to return
database.returnBlogThumbnails().then((blogs) => {
console.log(blogs);
//res.render('home', blogs);
});
});
正如我所說的,console.log吐出了我想要的東西。 但是,使用查詢調用該函數的函數始終顯示未定義。 謝謝
問題是您使用回調定義了函數,並試圖將其作為promise調用。 具有承諾的功能應為:
async function returnBlogThumbnails(filter = "recent") {
return new Promise((resolve, reject) => { // creates a promise
console.log("returning blogs")
//For now simply filter by most recent
if (filter === "recent") {
Blog.find({}).sort('-date').exec((err, docs) => {
if (err) {
reject(err);
} else {
resolve(docs)
}
});
}
});
}
然后在您的路線中可以將其稱為:
app.get('/', (req, res) => {
console.log("go home");
//Call out to query the database then use async function to return
database.returnBlogThumbnails()
.then((blogs) => {
console.log(blogs);
// do something with blogs
})
.catch((err) => {
console.log(err);
// handle error
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.