javascript - 循环通过承诺
问题描述
我正在尝试使用 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;
});
});
以上不起作用,因为承诺不是同步的。
解决方案
您可以map
在您的字段上创建一系列承诺。用于Promise.all
等待这些承诺解决,然后用于every
检查每个验证的响应状态。
我在这里使用过async
/ await
,但Promise.all(promises).then
效果同样好。我还模拟了一个演示验证例程,以便您可以看到它的实际效果。只需将解析从 'Valid' 更改为 'Invalid' 并重新运行演示以查看allValid
equal 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);
}
})();
推荐阅读
- python - 使用数据库使用python登录
- python - 数据显示不正确
- python - 在模式前用破折号重命名文件夹中的顺序文件(复制)?[Python]
- python - 如何使用python在xlsx中水平编写列表列表?
- identityserver4 - 使用 docker 启动 Identity Server 中的 X509Store 异常
- python - Python - 将文档粘贴到目录中的每个文件夹
- goland - 代码注释快捷方式不适用于 MacOS
- ruby-on-rails - 使用 Nokogiri 在 XML 中循环并获取子元素
- python - 如何获取给定的 dict 并为一个键返回一个具有多个值的新 dict?
- angular - 防止重新渲染角度分量