Home > OS >  How to run an if statement asynchronously
How to run an if statement asynchronously

Time:02-02

The following code is a long, branched if-statement. When I use node to run it, the console ouput is undefined (this behaviour is also replicated in the code snippet below). So essentially, the full if-statement isn't getting executed, and (I assume) the synchronous nature of javascript causes the function to end before the if-statement is executed in its totality. How can I wait for the if-statement to run before the function ends (maybe async-await or a promise)?

The code is as follows (it's a DIY date-validator that ensures dates are in the form DD/MM/YYYY and that the date is today's date or in the future):

function validDate(input){
    let monthLengths = [31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    if (input[2] !== "/" || input[5] !== "/"){
        return false;
    } else if (!Number.isInteger( input[0]) || !Number.isInteger( input[1]) || !Number.isInteger( input[3]) || !Number.isInteger( input[4]) || !Number.isInteger( input[6]) || !Number.isInteger( input[7]) || !Number.isInteger( input[8]) || !Number.isInteger( input[9])){
        return false;
    } else if (input.length !== 10){
        return false;
    } else if (input.substr(3, 2) === "02"){
        // check if leap year
        if ( input.substr(0, 2) > 29){
            return false;
        } else if (input.substr(0, 2) === "29" &&  input.substr(6, 4)%4 != 0){
            return false;
        }
    } else if ( input.substr(0, 2) > monthLengths[ input.substr(3, 2) - 1]){
        return false;
    } else if (Date.now() - Date.now()           
  •  Tags:  
  • Related