繁体   English   中英

Validate.js承诺自定义验证

[英]Validate.js promises on custom validation

我是承诺的新手,我想知道如何在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;

您需要从验证者返回承诺,然后解决承诺产品存在并拒绝它:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM