我是 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/