I have a page made up of multiple forms. Each form has it's own javascript file with a validate method like so.
function validateForm(){
return new Promise((resolve, reject) => {
fetch(urls.validate)
.then((r) => r.json())
.then((json) => {
if (json.Success){
resolve("Complete!");
}else{
resolve(json.ErrorHtml);
}
});
});
}
When the page loads, it loads up an array of the different javascript file methods to call like this.
var validationScripts = [];
validationScripts.push("eisForm.validateForm();");
validationScripts.push("background.validateForm();");
Finally, when the user gets to the last form the button needs to run all of the validation scripts.
async function runValidation(){
const results = await Promise.all(validationScripts.map(script => script()));
console.log(results);
}
This gives a TypeError: script is not a function error. I wasn't sure if it might be because each validateForm is followed by () and then in the map method it uses () again. I tried removing them from the array's push of each validateForm but I still get the same error.
I'm not sure how to make this work so that all of the Promises are awaited and the results const is a collection of all the resolved values.
Update
Here's an example.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<script>
var test = test || {};
test.eisForm = (() => {
async function validateForm(){
await fetch('https://jsonplaceholder.typicode.com/todos/1')
.then((response) => response.json())
.then((json) => {return json;});
}
return {
validateForm: validateForm
}
})();
test.background = (() => {
async function validateForm(){
await fetch('https://jsonplaceholder.typicode.com/todos/1')
.then((response) => response.json())
.then((json) => {return json;});
}
return {
validateForm: validateForm
}
})();
var validationScripts = [];
validationScripts.push(test.eisForm.validateForm);
validationScripts.push(test.background.validateForm);
async function runValidation(){
const results = await Promise.all(validationScripts.map(script => script()));
console.log(results);
}
window.onload = function(){
runValidation();
}
</script>
</body>
</html>
new Promise?!Promiseconstructor antipattern!