【问题标题】:Resolve all async promises with validate.js使用 validate.js 解决所有异步承诺
【发布时间】:2017-01-27 05:11:34
【问题描述】:

我正在使用这个库进行验证:https://validatejs.org/#validate-async

我有一个相当复杂的方法来根据自己的模式验证嵌套对象。请参阅下面的相关代码。

基本上,它会:

  1. 为每个嵌套对象创建一个异步承诺。
  2. 然后调用 Promise.all 来解决或拒绝验证。

它运行良好,除了一个问题。使用默认的 Promise 库 Promise.all“快速失败”,因此在后面的 express 中间件中的 catch 处理程序中,它只接收来自第一个失败的 Promise 的结果。但是为了让我的验证器工作,我需要结合所有失败的 Promise 的结果。

是否有替代的 Promise 库(符合 A+ 标准),我可以换成验证器来捕获所有错误?

ValidationAdapter.prototype.validateCreateCtrl = function(req, res, next){
  var obj = {};
  var self = this;
  this.logger.debug("Validating " + self.config.modelName + " create request");
  self.fieldList.forEach(function(fieldName){
    obj[fieldName] = req.body[fieldName];
  });

  self._resolveObjectRefs(obj);

  this.logger.debug("Composed request object " + JSON.stringify(obj, null, 2));

  var Promises = [];
  Promises.push(validate.async(obj, self.constraints));

  Object.keys(self.embeddedConstraints).forEach(function (key){
    var value = obj[key];
    var constraints = self.embeddedConstraints[key];
    if (value.constructor === Array){
      var i = 0;
      value.forEach(function(newVal){
        Promises.push(validate.async(newVal, constraints, {path: key + "[" + i + "]."}));
        i++;
      });
    }else{
      Promises.push(validate.async(value, constraints, {path: key}))
    }
  });

  // by default it should fall through
  Promise.all(Promises).then(function(){
    return next();
  }).catch(next);
};

【问题讨论】:

    标签: node.js promise validate.js


    【解决方案1】:

    你可以使用蓝鸟的反射来实现settleAll

    Promise.all(Promises.map(function(promise) {
        return promise.reflect();
    })).each(function(inspection) {
        if (inspection.isFulfilled()) {
            console.log("Success...");
        } else {
            console.error("Reject...");
        }
    });
    

    http://bluebirdjs.com/docs/api/reflect.html#reflect

    【讨论】:

      猜你喜欢
      • 2016-12-06
      • 1970-01-01
      • 2015-12-08
      • 2019-03-19
      • 2015-08-21
      • 2020-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多