Mongoose正确承诺拒绝处理 [英] Mongoose right promise rejection handling

查看:130
本文介绍了Mongoose正确承诺拒绝处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在nodeJS中与promise模式斗争

I'm bit fighting with promise pattern in nodeJS

我在db中寻找用户然后用用户引用保存新实体,但是当用户不是在db中,我应该返回拒绝,但我不确定如何正确地做到这一点。

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:抱歉,coffeescript: - [

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


推荐答案

你可以在然后回调中使用 throw 来拒绝它们。或者,您也可以使用 Promise 构造函数。 / JavaScript / Reference / Global_Objects / Promise / rejectrel =nofollow> Promise.reject(404)

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

这篇关于Mongoose正确承诺拒绝处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆