javascript - Validate.js promise 自定义验证

标签 javascript node.js promise bluebird

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

最佳答案

您需要从您的验证器返回一个 promise ,然后解析该 promise 产品是否存在,否则拒绝它:

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

关于javascript - Validate.js promise 自定义验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29121733/

相关文章:

javascript - 无法从 Shopify 调用 instagram API

javascript - 快速应用程序中未捕获的语法错误

javascript - 使用请求库使用自定义 header 进行 POST

javascript - 将 promise 转换为 Bluebird

javascript - 优化 JS 执行和浏览器帧率。 setTimeout(..., 0) 和 setTimeout(..., 1) 的行为不同

javascript - 如何调试不会从 MongoDB 检索数据的 JavaScript?

javascript - Angularjs ngMock 在每次测试之前或在每个测试用例上注入(inject)?

javascript - Ext JS 应用空白页

html - 从 Express/node.js Web 应用程序预填充 HTML/Jade

javascript - 使用 Promise jquery 自定义确认按钮