We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
最开始使用 Mongoose 的时候,对各种方法的返回结果不清楚,于是代码返回的不是期望中的结果。
因此就研究了一下 Mongoose 的几个常用 API,以及合理的使用方法。
在 Mongoose 中,不同的方法执行后的返回结果是不一样的。
.find() 方法本身返回的是一个 Query 类型的对象, .find().exec() 返回的才是 Promise 对象。
.find()
Query
.find().exec()
Promise
Mongoose find 方法的说明:Model.find()。
Google mongoose async await,在 Stack Overflow 上有篇问答可以参考:Using mongoose promises with async/await。
mongoose async await
重点理解:Using mongoose promises with async/await
由于 .find().exec() 返回的是 Promise 对象,要使用其中的值,方法本身要用 return 语句将 Promise 对象返回给调用它的方法。
return
而调用它的方法中,还要用 await 关键字执行这个被调用的方法获取最终执行结果。并且主调方法也要加上 async 关键字才行。
await
async
// 主调方法还需要加上 async 关键字 async function getToken() { try { // 异步执行的方法,所以加上 await 关键字才能写成同步执行的形式 let token = await getLocalToken() if (!token.access_token) { console.log(token) return token } else { // let token = await getNewToken() // let result= await saveToken() } return token } catch (error) { console.log(error) } } function getLocalToken () { // 返回 Promise 对象记得加 reutrn return TokenModel .find({}) .exec() // 调用 exec() 才会得到 Promise 对象 // 下面都是废代码!想想为什么? // .then(token => { // return token // }) // .catch(err => { // return 0 // }) }
待完成:
暂无
The text was updated successfully, but these errors were encountered:
No branches or pull requests
需求描述
最开始使用 Mongoose 的时候,对各种方法的返回结果不清楚,于是代码返回的不是期望中的结果。
因此就研究了一下 Mongoose 的几个常用 API,以及合理的使用方法。
方案调研
调研过程
在 Mongoose 中,不同的方法执行后的返回结果是不一样的。
.find()
方法本身返回的是一个Query
类型的对象,.find().exec()
返回的才是Promise
对象。Mongoose find 方法的说明:Model.find()。
Google
mongoose async await
,在 Stack Overflow 上有篇问答可以参考:Using mongoose promises with async/await。入选方案
应用过程
理论阐释
重点理解:Using mongoose promises with async/await
由于
.find().exec()
返回的是 Promise 对象,要使用其中的值,方法本身要用return
语句将 Promise 对象返回给调用它的方法。而调用它的方法中,还要用
await
关键字执行这个被调用的方法获取最终执行结果。并且主调方法也要加上async
关键字才行。实际代码
后续优化
待完成:
要点总结
暂无
The text was updated successfully, but these errors were encountered: