The code below is self explanatory. I have an array of validator functions coming in which can be either synchronous or async. I want to map over that array, await any promise that's required and return an array that contains all the results of the validator functions. I don't seem to be able to do this with the native .map()
const syncValidator = () => 'Valid';
const asyncValidator = async () => {
await new Promise(resolve => setTimeout(resolve, 1000));
return "Async validation error";
};
const validations = [syncValidator, asyncValidator];
// Function to find the results of all the validations
const validateSchema = async (validatorArray, inputValue) => {
const results = await validatorArray.map(
async validationFunc => {
const validation = await validationFunc(inputValue);
return validation;
}
);
return results;
}
(async () => {
const ans = await validateSchema(validations, 'blahblah');
// Expected answer: ['Valid', 'Async validation error']
console.log("Ans: ", ans)
// Incorrect answer: [ Promise {}, Promise {} ]
})();