簡體   English   中英

使用validate.js解決所有異步承諾

[英]Resolve all async promises with validate.js

我正在使用此庫進行驗證: https//validatejs.org/#validate-async

我有一種相當復雜的方法來驗證嵌套對象對自己的架構。 請參閱下面的相關代碼。

基本上,它將:

  1. 為每個嵌套對象創建一個異步承諾。
  2. 然后調用Promise.all來解析或拒絕驗證。

它運作良好,除了一個問題。 使用默認的promise庫Promise.all “快速失敗”,因此在catch處理程序(后面的快速中間件)中,它只接收來自第一個失敗的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);
};

您可以使用bluebird的反射來實現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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM