使用 Promises 时,每个 then() 应该返回一个值或抛出

新手上路,请多包涵

在从请求返回之前,我有一些异步方法需要等待完成。我正在使用 Promises,但我不断收到错误消息:

 Each then() should return a value or throw // promise/always-return

为什么会这样?这是我的代码:

 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
})

原文由 Tometoyou 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 575
2 个回答

只要避免 Promise 构造函数反模式!如果你不调用 resolve 但返回一个值,你将有一些东西 returnthen 方法应该用于 链接,而不仅仅是订阅

 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 => { … });
})

原文由 Bergi 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题