mongoose承诺如何跳到下一个.then()

时间:2015-07-26 11:46:29

标签: node.js mongoose promise

我正在使用以下代码实施电子邮件验证

//1. find the verificationInfo
VerificationInfo.findOne({user: req.user}).exec(function(err, verificationInfo) {
    if (err)
        return next(err)

    if (verificationInfo) {
        //2. if already have verification info
        var verificationLink = helper.urlWithQuery(req.baseUrl + '/verify', {token: verificationInfo.token})
        helper.sendEmail(email, 'verify your email', 'click the link: ' + verificationLink, function(err) {
            if (err)
                return next(helper.getGeneralError('unable to send email'))
            res.json({success: 'successfully sent email'})
        })
    }
    else {
        //3. no such verification info, create a new one
        var newVerificationInfo = new VerificationInfo()
        newVerificationInfo.user = req.user
        newVerificationInfo.token = helper.getUUID()
        newVerificationInfo.save(function(err) {
            if (err)
                return next(err)
            var verificationLink = helper.urlWithQuery(req.baseUrl + '/verify', {token: newVerificationInfo.token})
            helper.sendEmail(email, 'verify your email', 'click the link: ' + verificationLink, function(err) {
                if (err)
                    return next(helper.getGeneralError('unable to send email'))
                res.json({success: 'successfully sent email'})
            })
        })
    }
})

发送电子邮件部分重复。所以我更改此代码以使用像这样的承诺

VerificationInfo.findOne({user: req.user}).exec()
    .then(function(verificationInfo) {
        if (! verificationInfo) {
            var newVerificationInfo = new VerificationInfo()
            newVerificationInfo.user = req.user
            newVerificationInfo.token = helper.getUUID()
            req.token = newVerificationInfo.token
            return newVerificationInfo.save()
        }
        else {
            req.token = verificationInfo.token
            //TODO: HOW TO GET TO THE NEXT .then()
        }
    })
    .then(function() {
        var verificationLink = helper.urlWithQuery(req.baseUrl + '/verify', {token: req.token})
        helper.sendEmail(email, 'verify your email', 'click the link: ' + verificationLink, function(err) {
            if (err)
                return next(helper.getGeneralError('unable to send email'))
            res.json({success: 'successfully sent email'})
        })
    })
    .then(null, function(err) {
        return next(err)
    })

如我的评论所示,如果verifyInfo已经存在,我怎么能去下一个.then()?

1 个答案:

答案 0 :(得分:0)

这是其他地方的一个错误。我已经决定删除​​存在检查。如果用户发送多个请求,我只需创建一个新请求,因为它很快就会过期并被mongoose自动删除