首页 > 解决方案 > 循环通过承诺

问题描述

我正在尝试使用 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;
    });
  });

以上不起作用,因为承诺不是同步的。

标签: javascriptformspromiseformvalidation.io

解决方案


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

我在这里使用过async/ await,但Promise.all(promises).then效果同样好。我还模拟了一个演示验证例程,以便您可以看到它的实际效果。只需将解析从 'Valid' 更改为 'Invalid' 并重新运行演示以查看allValidequal 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);
  }
})();


推荐阅读