【发布时间】:2015-05-21 05:14:06
【问题描述】:
我是 Promise 的新手,我想知道如何在 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.js,它的.async方法有什么作用?
标签: javascript node.js promise bluebird