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;