问题
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