Mongoose right promise rejection handling

倾然丶 夕夏残阳落幕 提交于 2019-12-23 12:14:25

问题


I'm bit fighting with promise pattern in nodeJS

I'm looking for user in db and then saving new entity with user reference, but when user is not in db, I should return rejection, but I'm not sure how to do it properly.

is there way how to do it more nicely?

btw: sorry, coffeescript :-[

User.findOne({'fbId':userData.me.id}).exec().then((doc)->
  if !doc? then return new Promise (resolve,reject)->reject(404)

  video = new Video({
    user:doc
    state: "queue"
    createdAt: new Date()
  })

  video.save().exec()
)

回答1:


You can use throw inside then callbacks to reject them. Or, instead of using the Promise constructor like that, you might also use Promise.reject(404).

User.findOne
  fbId:userData.me.id 
.exec().then (doc)->
  if !doc? 
    throw new Error 404

  video = new Video
    user: doc
    state: "queue"
    createdAt: new Date
  video.save().exec()


来源:https://stackoverflow.com/questions/28695092/mongoose-right-promise-rejection-handling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!