[英]how can I use var out of model.find(), Mongoose
I want to use var bot_man
how can I pass to out of function.我想使用 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 is '' result =
结果是''
result =
Post.find
is an asynchronous function. Post.find
是一个异步 function。 When you call it it with a callback it defers callback's execution untill the result is ready (somewhere in the future) and immediatelly proceeds to the next line.当您使用回调调用它时,它会延迟回调的执行,直到结果准备好(将来的某个地方)并立即进入下一行。 Thus
bot_man
is still an empty string when evaluated in console.log('result = ${bot_man}')
.因此
bot_man
在console.log('result = ${bot_man}')
中评估时仍然是一个空字符串。
To get the result you'd better off making your function async
and rewrite it as:为了得到结果,你最好让你的 function
async
并将其重写为:
let author = await Post.find({ title: 'bot_status' }).exec()
let bot_man = author[0].body
console.log(`result = ${bot_man}`)
Though for production code it still lacks some sanity checks.尽管对于生产代码,它仍然缺乏一些健全性检查。 Whether
author
is not null or empty and error handling. author
是不是 null 还是空和错误处理。 I didn't include them into the snippet to not complicate the code.我没有将它们包含在代码段中,以免使代码复杂化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.