简体   繁体   中英

Validate.js promises on custom validation

I am new to promises and I would like to know how I could simulate something like await on C#.

Problem is that when I validate my payload product it does validate if its present, however when I try to validate if it exist in database it skips it since I query the database async and I think it goes through it.

Here is my code, is there any way of making it wait for response from database?

'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;

You need to return a promise from your validator, then resolve the promise product exists and reject it otherwise:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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