每个then()应该在使用Promises时返回一个值或throw

Tom*_*you 12 javascript node.js

在我从请求返回之前,我需要等待完成的一些异步方法.我正在使用Promises,但我一直收到错误:

Each then() should return a value or throw // promise/always-return
Run Code Online (Sandbox Code Playgroud)

这为什么开心呢?这是我的代码:

router.get('/account', function(req, res) {
  var id = req.user.uid
  var myProfile = {}
  var profilePromise = new Promise(function(resolve, reject) {
    var userRef = firebase.db.collection('users').doc(id)
    userRef.get()
      .then(doc => { // Error occurs on this line
        if (doc.exists) {
          var profile = doc.data()
          profile.id = doc.id
          myProfile = profile
          resolve()
        } else {
          reject(Error("Profile doesn't exist"))
        }
      })
      .catch(error => {
        reject(error)
      })
  })
  // More promises further on, which I wait for
})
Run Code Online (Sandbox Code Playgroud)

Ber*_*rgi 12

只是避免Promise构造函数反模式!如果您不打电话resolve但返回一个值,那么您将有所收获return.该then方法应该用于链接,而不仅仅是订阅:

outer.get('/account', function(req, res) {
  var id = req.user.uid
  var userRef = firebase.db.collection('users').doc(id)
  var profilePromise = userRef.get().then(doc => {
    if (doc.exists) {
      var profile = doc.data()
      profile.id = doc.id
      return profile // I assume you don't want to return undefined
//    ^^^^^^
    } else {
      throw new Error("Profile doesn't exist")
//    ^^^^^
    }
  })
  // More promises further on, which I wait for:
  // profilePromise.then(myProfile => { … });
})
Run Code Online (Sandbox Code Playgroud)