Skip to content
New issue

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 异步执行 #32

Closed
Dream4ever opened this issue Jun 3, 2018 · 0 comments
Closed

Mongoose 异步执行 #32

Dream4ever opened this issue Jun 3, 2018 · 0 comments
Labels
Back-end Where data really come and go JS Javascript

Comments

@Dream4ever
Copy link
Owner

需求描述

最开始使用 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 关键字才行。

实际代码

// 主调方法还需要加上 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
    // })
}

后续优化

待完成:

要点总结

暂无

@Dream4ever Dream4ever added Back-end Where data really come and go JS Javascript labels Jun 3, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Back-end Where data really come and go JS Javascript
Projects
None yet
Development

No branches or pull requests

1 participant