0

I'm currently trying to add a rejected promise to my promises array if one of my checks fails. The problem is that the function to check if all checks are valid fails. This is my code:

let invalidPromises      = [],
    validationPromises   = [];

if ( input.val() === "" ) {
    invalidPromises.push( Promise.reject() );
} else if ( validationAllowed( invalidPromises ) )
    .......

console.log( validationAllowed( invalidPromises ) );

function validationAllowed( invalidPromises ) {
    Promise.all( invalidPromises ).then( () => {
        return true;
    } ).catch( () => {
        return false;
    } );
}

The output of the console.log should be false but I'm getting only undefined. Any idea what I'm doing wrong?

Mr. Jo
  • 4,946
  • 6
  • 41
  • 100
  • 2
    `validationAllowed` isn't returning anything. Have it return the `Promise.all` call, and then call `.then` on it to consume the Promise and get the value it resolves to. `return Promise.all` and `validationAllowed(invalidPromises).then(console.log)` – CertainPerformance Sep 15 '19 at 23:20
  • 1
    As @CertainPerformance has said, you just need to change the line to `return Promise.all( invalidPromises ).then( () => {` and it will work as you'd expect it – Niro Sep 15 '19 at 23:22
  • But how can I use the validationAllowed() function inside an if() now when I'm returning a promise and not a boolean? – Mr. Jo Sep 15 '19 at 23:23
  • `if (await validationAllowed(invalidPromises))` is one way to do it, but the better one is to have the promise `resolve()` when valid and `reject(error)` on errors. Then you'd use a `try {} catch{}` block to deal with invalid input. – Niro Sep 15 '19 at 23:27
  • 1
    @Mr.Jo Just stop using promises if you're not planning to do anything asynchronous? – Bergi Sep 15 '19 at 23:30

0 Answers0