遍历承诺

时间:2019-01-24 00:05:25

标签: javascript forms promise formvalidation.io

我正在尝试使用formvalidation.io验证10个表单字段。如果10个验证中的任何一个失败,我都需要返回false。但是,要访问验证是否已通过,您需要打电话给Promise。

var otherFacilityFields = [
    "addressLine1",
    "city"
];

  fieldsPass = otherFacilityFields.every(function(field) {
    fv.validateField(field).then(function(status) {
        if (status != 'Valid') {
            return false;
        }
        return true;
    });
  });

以上操作无效,因为承诺不同步。

2 个答案:

答案 0 :(得分:3)

您可以map在您的字段上创建一个诺言数组。使用Promise.all等待这些承诺解决,然后然后使用every检查每个验证的响应状态。

我在这里使用了async / await,但是Promise.all(promises).then可以同样有效地工作。我还模拟了演示验证例程,以便您可以实际查看它。只需将解析度从“有效”更改为“无效”,然后重新运行演示以查看allValid等于false

const fv = {
  validateField() {
    return new Promise(resolve => {
      setTimeout(() => resolve('Valid'), 1000);
    });
  }
}

const otherFacilityFields = ['addressLine1', 'city'];

// `map` over the fields and return a
// validation promise for each
const promises = otherFacilityFields.map(field => {
  return fv.validateField(field);
});

(async () => {
  try {

    // await the promises to all resolve
    const res = await Promise.all(promises);

    // Use `every` to check the status of each validation
    const allValid = res.every(status => status === 'Valid');
    console.log(allValid);
  } catch (e) {
    console.log(e);
  }
})();

答案 1 :(得分:0)

如果您使用的是javascript具有异步功能,请等待

fieldsPass = otherFacilityFields.every(async function(field) {
    let status = await fv.validateField(field)
    if (status != 'Valid') {
        return false;
    }
    return true;
  });

或者您可以使用Promise.all()尝试一些解决方案
或者您可以使用全局变量,如

  let valid = true
  let length = otherFacilityFields.length
  fieldsPass = otherFacilityFields.every(function(field) {
    fv.validateField(field).then(function(status) {
        if (status != 'Valid') {
            valid = false;
        }
        valid = true;
        length = length - 1
        if(length == 0)
          //return the valid value
    });
  });

相关问题