Home > other >  How to reject a input value in a function if it is null in javascript
How to reject a input value in a function if it is null in javascript

Time:10-06

Hi i have a function like this

class Fun {
 pem_Files_Checker_And_Adder_Server_Id_Adder(id , serverType , hostname) {
      //do something
  };
 };
}

In this function i can give values to it to properly work

Like

new Fun().pem_Files_Checker_And_Adder_Server_Id_Adder("id" , "servertype" , "hostname");

What i want is if these supplied values is null or empty like this

new Fun().pem_Files_Checker_And_Adder_Server_Id_Adder("" , "" , "");

I want to throw a error saying "please add value"

I can do it like this

class Fun {
    pem_Files_Checker_And_Adder_Server_Id_Adder(id, serverType, hostname) {
    return new Promise(async (resolve, reject) => {
        if (typeof id !== "undefined" && id !== "" && id !== null) {
            if (typeof serverType !== "undefined" && serverType !== "" && serverType !== null) {
                if (typeof hostname !== "undefined" && hostname !== "" && hostname !== null) {
                      //do something if values are supplied
                } else {
                    reject("Please add value to Hostname");
                };
            } else {
                reject("Please add value to serverType")
            };
        } else {
            reject("Please add value to id");
        };
    });
};
}

This works for me. But This looks a little bit ugly

Is there a another way to do this. I am new to Javascript

CodePudding user response:

If you want all the errors you can use an array and push errors to it. If the errors has a length you can reject it.

return new Promise(async (resolve, reject) => {
    const errors = [];

    if (!id) errors.push('Please add value to id');
    if (!serverType) errors.push('Please add value to serverType');
    if (!hostname) errors.push('Please add value to Hostname');

    if (errors.length) return reject(errors);
    
    resolve('it is valid');
});

CodePudding user response:

You can build a list of missing argument names, and then use it to create an error message which informs the caller of any missing arguments:

class Fun {
  async pem_Files_Checker_And_Adder_Server_Id_Adder (id, serverType, hostname) {
    const missingArgNames = [];

    for (const [arg, name] of [
      [id, 'id'],
      [serverType, 'serverType'],
      [hostname, 'hostname'],
    ]) if (!arg) missingArgNames.push(name);

    if (missingArgNames.length > 0) {
      throw new Error(`Missing arguments: ${missingArgNames.join(', ')}`);
    }

    // Continue if all values are present
  }
}

new Fun().pem_Files_Checker_And_Adder_Server_Id_Adder(1).catch(console.error);

CodePudding user response:

This is sometimes called "if-else hell", similar to callback hell. In your case, it's pretty easy to get out of. You just need to acknowledge that you don't need to do anything after the reject. So, what does "not doing anything mean after" mean in a function? That can be summarized as a return statement!

return new Promise(async (resolve, reject) => {
    if (typeof id == "undefined" || id == "" || id === null) 
        return reject("Please add value to id");

    if (typeof serverType === "undefined" || serverType === "" || serverType === null)
        return reject("Please add value to serverType");

    if (typeof hostname !== "undefined" && hostname !== "" && hostname !== null)
        return reject("Please add value to Hostname");

    // do stuff now :)
});

Much cleaner now, ey? You might also want to consider turning the repetitive conditions into a function, or even simplifying them to just !id, !serverType, and !hostname, since you're just checking if they're not a falsy value.

Note: I have used DeMorgan's laws to simplify the conditions. Basically, "A and B" is the same as "not A or not B".


P.S. Why are you using async with new Promise? You don't need new Promise then, if you're going to use async/await anyways. Just add async to your method:

async pem_Files_Checker_And_Adder_Server_Id_Adder(id , serverType , hostname) {

Then you don't need new Promise that takes an async callback anyways.

  • Related