【问题标题】:Validate.js promises on custom validationValidate.js 对自定义验证的承诺
【发布时间】:2015-05-21 05:14:06
【问题描述】:

我是 Promise 的新手,我想知道如何在 C# 上模拟 await 之类的东西。

问题是,当我验证我的有效负载 product 时,它会验证它是否存在,但是当我尝试验证它是否存在于数据库中时,它会跳过它,因为我异步查询数据库并且我认为它会通过它。

这是我的代码,有什么办法让它等待数据库的响应?

'use strict';

var Validate = require('validate.js');
var Promise = require('bluebird');

function ValidateLoanCreate(payload) {
    if (!(this instanceof ValidateLoanCreate)) {
        return new ValidateLoanCreate(payload);
    }

    return new Promise(function(resolve, reject) {

        Validate.validators.productExists = function(value, options, key, attributes) {
            // Would like to HALT execution here a.k.a. 'await'
            Product.findOne().where({ id : value })
                .then(function(product) {
                    if (_.isUndefined(product)) {
                        return 'does not exist in database';
                    }
                })
                .catch(function(e) {
                    reject(e);
                });
        };

        Validate.async(payload, {
            product: {
                presence: true,
                productExists: true // This does not work because it's async
            }
        }).then(function(success, error) {
            resolve();
        }).catch(function(e) {
            reject(e);
        })
    });
}

module.exports = ValidateLoanCreate;

【问题讨论】:

标签: javascript node.js promise bluebird


【解决方案1】:

你需要从你的验证器返回一个承诺,然后解决承诺产品存在,否则拒绝它:

Validate.validators.productExists = function(value) {
    return Validate.promise(function(res, rej) {
        Product.findOne().where({ id : value })
            .then(function(product) {
                if (_.isUndefined(product)) {
                    rej('does not exist in database');
                }
                else {
                    res();
                }
            });
     });
 };

【讨论】:

    猜你喜欢
    • 2018-06-21
    • 2017-04-06
    • 2017-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-30
    相关资源
    最近更新 更多