[英]how can I use var out of model.find(), Mongoose
我想使用 var bot_man
如何從 function 中傳遞出去。
var bot_man = ''
Post.find({ title: 'bot_status' }, function (err, author) {
if (err) throw err
bot_man = author[0].body
console.log(author[0].body) //output => 'on'
})
console.log(`result = ${bot_man}`) // result =
結果是'' result =
Post.find
是一個異步 function。 當您使用回調調用它時,它會延遲回調的執行,直到結果准備好(將來的某個地方)並立即進入下一行。 因此bot_man
在console.log('result = ${bot_man}')
中評估時仍然是一個空字符串。
為了得到結果,你最好讓你的 function async
並將其重寫為:
let author = await Post.find({ title: 'bot_status' }).exec()
let bot_man = author[0].body
console.log(`result = ${bot_man}`)
盡管對於生產代碼,它仍然缺乏一些健全性檢查。 author
是不是 null 還是空和錯誤處理。 我沒有將它們包含在代碼段中,以免使代碼復雜化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.